Java Code Examples for org.apache.http.util.EntityUtils.toByteArray()

The following are Jave code examples for showing how to use toByteArray() of the org.apache.http.util.EntityUtils class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: Thrush   File: HttpRequest.java   View Source Code Vote up 7 votes
private static byte[] captchaImage(String url) {
    Objects.requireNonNull(url);

    CloseableHttpClient httpClient = buildHttpClient();
    HttpGet httpGet = new HttpGet(url);

    httpGet.addHeader(CookieManager.cookieHeader());

    byte[] result = new byte[0];
    try (CloseableHttpResponse response = httpClient.execute(httpGet)) {
        CookieManager.touch(response);
        result = EntityUtils.toByteArray(response.getEntity());
    } catch (IOException e) {
        logger.error("captchaImage error", e);
    }

    return result;
}
 
Example 2
Project: elasticsearch_my   File: ClientYamlTestResponse.java   View Source Code Vote up 7 votes
ClientYamlTestResponse(Response response) throws IOException {
    this.response = response;
    if (response.getEntity() != null) {
        String contentType = response.getHeader("Content-Type");
        this.bodyContentType = XContentType.fromMediaTypeOrFormat(contentType);
        try {
            byte[] bytes = EntityUtils.toByteArray(response.getEntity());
            //skip parsing if we got text back (e.g. if we called _cat apis)
            if (bodyContentType != null) {
                this.parsedResponse = ObjectPath.createFromXContent(bodyContentType.xContent(), new BytesArray(bytes));
            }
            this.body = bytes;
        } catch (IOException e) {
            EntityUtils.consumeQuietly(response.getEntity());
            throw e;
        }
    } else {
        this.body = null;
        this.bodyContentType = null;
    }
}
 
Example 3
Project: FreeStreams-TVLauncher   File: HttpResult.java   View Source Code Vote up 7 votes
public HttpResult(HttpResponse httpResponse, CookieStore cookieStore) {
	if (cookieStore != null) {
		this.cookies = cookieStore.getCookies().toArray(new Cookie[0]);
	}

	if (httpResponse != null) {
		this.headers = httpResponse.getAllHeaders();
		this.statuCode = httpResponse.getStatusLine().getStatusCode();
		if(d)System.out.println(this.statuCode);
		try {
			this.response = EntityUtils.toByteArray(httpResponse
					.getEntity());
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}
 
Example 4
Project: integration-test-helper   File: Response.java   View Source Code Vote up 7 votes
/**
 * Constructor
 *
 * @param response the http response
 */
public Response( final HttpResponse response )
{
	this.status = response.getStatusLine( );
	this.headers = response.getAllHeaders( );

	try
	{
		this.entityContent = EntityUtils.toByteArray( response.getEntity( ) );
		// EntityUtils.consume( response.getEntity( ) );
	}
	catch ( IllegalArgumentException | IOException e )
	{
		// ok
	}
}
 
Example 5
Project: kiqr   File: GenericBlockingRestKiqrClientImpl.java   View Source Code Vote up 7 votes
private <U> U execute(URISupplier<URI> uriSupplier, MappingFunction<byte[], U> responseMapper, Supplier<U> notFoundMapper) {
    try {
        URI uri = uriSupplier.get();
        Request request = Request.Get(uri);
        HttpResponse response = request.execute().returnResponse();

        if (response.getStatusLine().getStatusCode() == 200) {
            byte[] returnJson = EntityUtils.toByteArray(response.getEntity());

            return responseMapper.apply(returnJson);


        } else if (response.getStatusLine().getStatusCode() == 404) {
            return notFoundMapper.get();
        } else if (response.getStatusLine().getStatusCode() == 400) {
            throw new IllegalArgumentException("Bad Request");
        } else {
            throw new QueryExecutionException("Something went wrong, status code: " + response.getStatusLine().getStatusCode());
        }


    } catch (URISyntaxException | IOException e) {
        throw new ConnectionException("Error creating connection", e);
    }

}
 
Example 6
Project: framework   File: HttpUtils.java   View Source Code Vote up 6 votes
/**
 * 下载文件
 *
 * @param url URL
 * @return 文件的二进制流,客户端使用outputStream输出为文件
 */
public static byte[] getFile(String url) {
	try {
		Request request = Request.Get(url);
		HttpEntity resEntity = request.execute().returnResponse().getEntity();
		return EntityUtils.toByteArray(resEntity);
	} catch (Exception e) {
		logger.error("postFile请求异常," + e.getMessage() + "\n post url:" + url);
		e.printStackTrace();
	}
	return null;
}
 
Example 7
Project: Hotspot-master-devp   File: SecurityUtil.java   View Source Code Vote up 6 votes
/**
 * 
 * @param entity
 * @return
 */
public static byte[] decryptHttpEntity(HttpEntity entity) {
    byte[] buffer = null;
    try {
        buffer = EntityUtils.toByteArray(entity);
    } catch (IOException e) {
        e.printStackTrace();
    }
    if (buffer != null) {
        return new Crypter().decrypt(buffer, SECRET_KEY_HTTP);
    }
    return buffer;
}
 
Example 8
Project: datarouter   File: DefaultSignatureValidator.java   View Source Code Vote up 6 votes
private byte[] signWithoutSettingParameterOrder(Map<String, String> map, HttpEntity entity){
	// TODO signature length should be constant. currently signature length is proportional to number of parameters.
	ByteArrayOutputStream signature = new ByteArrayOutputStream();
	try{
		MessageDigest md = MessageDigest.getInstance(HASHING_ALGORITHM);
		for(Entry<String,String> entry : map.entrySet()){
			String parameterName = entry.getKey();
			if(parameterName.equals(SecurityParameters.SIGNATURE) || "submitAction".equals(parameterName)){
				continue;
			}
			String value = entry.getValue();
			String keyValue = parameterName.concat(value == null ? "" : value);
			String keyValueSalt = keyValue.concat(salt);
			md.update(keyValueSalt.getBytes(StandardCharsets.UTF_8));
			signature.write(md.digest());
		}

		if(entity != null){
			byte[] bytes = EntityUtils.toByteArray(entity);
			md.update(bytes);
			md.update(salt.getBytes(StandardCharsets.UTF_8));
			signature.write(md.digest());
		}
	}catch(IOException | NoSuchAlgorithmException e){
		throw new RuntimeException(e);
	}
	return signature.toByteArray();
}
 
Example 9
Project: datarouter   File: CachingHttpServletRequest.java   View Source Code Vote up 6 votes
public byte[] getContent() throws IOException{
	if(content != null){
		return content;
	}

	// don't close stream
	content = EntityUtils.toByteArray(new InputStreamEntity(super.getInputStream()));
	return content;
}
 
Example 10
Project: lams   File: BufferedHttpEntity.java   View Source Code Vote up 6 votes
/**
 * Creates a new buffered entity wrapper.
 *
 * @param entity   the entity to wrap, not null
 * @throws IllegalArgumentException if wrapped is null
 */
public BufferedHttpEntity(final HttpEntity entity) throws IOException {
    super(entity);
    if (!entity.isRepeatable() || entity.getContentLength() < 0) {
        this.buffer = EntityUtils.toByteArray(entity);
    } else {
        this.buffer = null;
    }
}
 
Example 11
Project: bubble2   File: ResponseWrap.java   View Source Code Vote up 6 votes
/**
 * 获取响应内容为字节数组
 * 
 * 
 * @date 2015年7月17日
 * @return
 */
public byte[] getByteArray() {
	try {
		return EntityUtils.toByteArray(entity);
	} catch (ParseException | IOException e) {
		logger.error(e.getMessage(), e);
		throw new RuntimeException(e.getMessage(), e);
	}
}
 
Example 12
Project: QuickHttp   File: HttpResponseBody.java   View Source Code Vote up 6 votes
private byte[] bytes(HttpEntity entity){
    try {
        return EntityUtils.toByteArray(entity);
    } catch (IOException e) {
        error(e);
    }
    return null;
}
 
Example 13
Project: java-restclient   File: HTTPCUtil.java   View Source Code Vote up 6 votes
public static byte[] handleResponse(HttpResponse response) throws IOException {
    HttpEntity entity = response.getEntity();
    if (entity == null) return null;

    byte[] output = EntityUtils.toByteArray(entity);
    EntityUtils.consume(entity);

    return output;
}
 
Example 14
Project: java-restclient   File: HTTPCMockHandler.java   View Source Code Vote up 6 votes
private byte[] parseRequestBody(HttpRequest request) throws IOException {
    HttpEntity entity = null;
    if (request instanceof HttpEntityEnclosingRequest)
        entity = ((HttpEntityEnclosingRequest) request).getEntity();

    return entity != null ? EntityUtils.toByteArray(entity) : null;
}
 
Example 15
Project: firebase-admin-java   File: IntegrationTestUtils.java   View Source Code Vote up 5 votes
private ResponseInfo(HttpResponse response) throws IOException {
  this.status = response.getStatusLine().getStatusCode();
  this.payload = EntityUtils.toByteArray(response.getEntity());
}
 
Example 16
Project: elasticsearch_my   File: ObjectPath.java   View Source Code Vote up 5 votes
public static ObjectPath createFromResponse(Response response) throws IOException {
    byte[] bytes = EntityUtils.toByteArray(response.getEntity());
    String contentType = response.getHeader("Content-Type");
    XContentType xContentType = XContentType.fromMediaTypeOrFormat(contentType);
    return ObjectPath.createFromXContent(xContentType.xContent(), new BytesArray(bytes));
}
 
Example 17
Project: outcomes   File: TestHttpCore.java   View Source Code Vote up 2 votes
@Test
public void entities() throws IOException {

    StringEntity entity = new StringEntity("important message", Consts.UTF_8);

    EntityUtils.toString(entity);
    EntityUtils.toByteArray(entity);

    StringBuilder sb = new StringBuilder();
    Map<String, String> env = System.getenv();
    for (Map.Entry<String, String> envEntry : env.entrySet()) {
        sb.append(envEntry.getKey())
                .append(": ").append(envEntry.getValue())
                .append("\r\n");
    }

    // construct without a character encoding (defaults to ISO-8859-1)
    HttpEntity myEntity1 = new StringEntity(sb.toString());

    // alternatively construct with an encoding (mime type defaults to "text/plain")
    HttpEntity myEntity2 = new StringEntity(sb.toString(), Consts.UTF_8);

    // alternatively construct with an encoding and a mime type
    HttpEntity myEntity3 = new StringEntity(sb.toString(),
            ContentType.create("text/plain", Consts.UTF_8));

    BasicHttpEntity myEntity = new BasicHttpEntity();
    myEntity.setContent(new FileInputStream(""));
    myEntity.setContentLength(340); // sets the length to 340

    new ByteArrayEntity(new byte[] {1,2,3},
            ContentType.APPLICATION_OCTET_STREAM);

    new FileEntity(new File(""),
            ContentType.create("application/java-archive"));
}