@Override public byte[] getResponseBodyAsBytes() throws IOException { if (entity == null) { return null; } return EntityUtils.toByteArray(entity); }
public static byte[] responseToByteArray( HttpResponse response ) throws IOException { return EntityUtils.toByteArray( response.getEntity() ); }
private byte[] getEntityAsByteArray(HttpEntity entity) { try { return EntityUtils.toByteArray(entity); } catch (IOException e) { throw new RuntimeException(e); } }
public BufferedHttpEntity(final HttpEntity entity) throws IOException { super(entity); if (!entity.isRepeatable() || entity.getContentLength() < 0) { this.buffer = EntityUtils.toByteArray(entity); } else { this.buffer = null; } }
byte[] getBytes() { if (request instanceof HttpEntityEnclosingRequestBase) { try { HttpEntity entity = ((HttpEntityEnclosingRequestBase) request).getEntity(); return EntityUtils.toByteArray(entity); } catch (IOException e) { throw new UndeclaredThrowableException(e); } } return EMPTY_BYTES; } }
private static BufferedImage getImage(CloseableHttpResponse httpResponse) { try { int status = httpResponse.getStatusLine().getStatusCode(); if (status == 200) { byte[] bytes = EntityUtils.toByteArray(httpResponse.getEntity()); return ImageIO.read(new ByteArrayInputStream(bytes)); } } catch (IOException e) { logger.error("", e); } finally { try { httpResponse.close(); } catch (IOException e) { logger.error("", e); } } return null; }
return EntityUtils.toByteArray(response.getEntity()); } else { String errorMsg = EntityUtils.toString(response.getEntity());
private byte[] getResponseBody(HttpResponse response, boolean verifyResponse) throws IOException, GeneralSecurityException { HttpEntity resEntity = response.getEntity(); if (resEntity != null) { byte[] body = EntityUtils.toByteArray(resEntity); EntityUtils.consume(resEntity); if (verifyResponse) { Header signatureHeader = response .getFirstHeader(CommonEpConstans.SIGNATURE_HEADER_NAME); if (signatureHeader == null) { throw new IOException("can't verify message"); } byte[] signature; if (signatureHeader.getValue() != null) { signature = Base64.decodeBase64(signatureHeader.getValue() .getBytes(Charsets.UTF_8)); } else { signature = new byte[0]; } return verifyResponse(body, signature); } else { return body; } } else { throw new IOException("can't read message"); } }
private byte[] getImage(String url) { // Try to get the fiveicon from the url using an HTTP connection from the pool // that also allows to configure timeout values (e.g. connect and get data) final RequestConfig requestConfig = RequestConfig.custom() .setConnectTimeout(2000) .setSocketTimeout(2000) .build(); final HttpUriRequest getRequest = RequestBuilder.get(url) .setConfig(requestConfig) .build(); try(final CloseableHttpResponse response = client.execute(getRequest)) { if(response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { return EntityUtils.toByteArray(response.getEntity()); } } catch (final IOException ignored) { // Do nothing } return null; }
protected void testLarge(String path) throws IOException { try (CloseableHttpClient hc = HttpClients.createMinimal()) { try (CloseableHttpResponse res = hc.execute(new HttpGet(server().uri(path)))) { assertThat(res.getStatusLine().toString()).isEqualTo("HTTP/1.1 200 OK"); assertThat(res.getFirstHeader(HttpHeaderNames.CONTENT_TYPE.toString()).getValue()) .startsWith("text/plain"); final byte[] content = EntityUtils.toByteArray(res.getEntity()); // Check if the content-length header matches. assertThat(res.getFirstHeader(HttpHeaderNames.CONTENT_LENGTH.toString()).getValue()) .isEqualTo(String.valueOf(content.length)); // Check if the content contains what's expected. assertThat(Arrays.stream(CR_OR_LF.split(new String(content, StandardCharsets.UTF_8))) .map(String::trim) .filter(s -> !s.isEmpty()) .count()).isEqualTo(1024); } } } }
private HttpResponse setupNormalResponse(final org.apache.http.HttpResponse remoteResponse) throws IOException { HttpVersion httpVersion = HttpVersion.valueOf(remoteResponse.getProtocolVersion().toString()); HttpResponseStatus status = HttpResponseStatus.valueOf(remoteResponse.getStatusLine().getStatusCode()); FullHttpResponse response = new DefaultFullHttpResponse(httpVersion, status); response.setStatus(status); Header[] allHeaders = remoteResponse.getAllHeaders(); for (Header header : allHeaders) { if (isResponseHeader(header)) { response.headers().set(header.getName(), header.getValue()); } } HttpEntity entity = remoteResponse.getEntity(); if (entity != null) { byte[] content = toByteArray(entity); if (content.length > 0) { ByteBuf buffer = Unpooled.copiedBuffer(content); response.content().writeBytes(buffer); } } return newResponse(response); }
@Override public boolean getQR(String qrPath) { qrPath = qrPath + File.separator + "QR.jpg"; String qrUrl = URLEnum.QRCODE_URL.getUrl() + core.getUuid(); HttpEntity entity = myHttpClient.doGet(qrUrl, null, true, null); try { OutputStream out = new FileOutputStream(qrPath); byte[] bytes = EntityUtils.toByteArray(entity); out.write(bytes); out.flush(); out.close(); try { CommonTools.printQr(qrPath); // 打开登陆二维码图片 } catch (Exception e) { LOG.info(e.getMessage()); } } catch (Exception e) { LOG.info(e.getMessage()); return false; } return true; }
/** * 上传图文消息内的图片获取URL * 请注意,本接口所上传的图片不占用公众号的素材库中图片数量的5000个的限制。图片仅支持jpg/png格式,大小必须在1MB以下。 * @param access_token access_token * @param uri uri * @return UploadimgResult */ public static UploadimgResult mediaUploadimg(String access_token,URI uri){ HttpPost httpPost = new HttpPost(BASE_URI+"/cgi-bin/media/uploadimg"); CloseableHttpClient tempHttpClient = HttpClients.createDefault(); try { HttpEntity entity = tempHttpClient.execute(RequestBuilder.get().setUri(uri).build()).getEntity(); HttpEntity reqEntity = MultipartEntityBuilder.create() .addBinaryBody("media",EntityUtils.toByteArray(entity),ContentType.get(entity),UUID.randomUUID().toString()+".jpg") .addTextBody(PARAM_ACCESS_TOKEN, API.accessToken(access_token)) .build(); httpPost.setEntity(reqEntity); return LocalHttpClient.executeJsonResult(httpPost,UploadimgResult.class); } catch (Exception e) { logger.error("", e); } finally{ try { tempHttpClient.close(); } catch (Exception e) { logger.error("", e); } } return null; }
public Response expect(final byte[] content) throws Exception { assertArrayEquals(content, EntityUtils.toByteArray(this.rsp.getEntity())); return this; }
assertEquals("an_example_body", new String(EntityUtils.toByteArray(response.getEntity()), StandardCharsets.UTF_8));
); HttpResponse response = httpClient.execute(request); assertThat(new String(EntityUtils.toByteArray(response.getEntity()), UTF_8), is("some_body")); assertThat(response.getStatusLine().getStatusCode(), is(OK_200.code())); ); response = httpClient.execute(request); assertThat(new String(EntityUtils.toByteArray(response.getEntity()), UTF_8), is(""));
@Test public void shouldReturnResponseByMatchingStringBody() throws IOException, URISyntaxException { // when getMockServerClient() .when( request() .withBody( exact("some_random_body") ), Times.exactly(2) ) .respond( response() .withBody("some_string_body_response") ); // then HttpClient httpClient = createHttpClient(); HttpPost request = new HttpPost( new URIBuilder() .setScheme("http") .setHost("localhost") .setPort(getServerPort()) .setPath(addContextToPath("some_path")) .build() ); request.setEntity(new StringEntity("some_random_body")); HttpResponse response = httpClient.execute(request); assertThat(new String(EntityUtils.toByteArray(response.getEntity()), UTF_8), is("some_string_body_response")); assertThat(response.getStatusLine().getStatusCode(), is(OK_200.code())); }
public byte[] getAsBytes(final String url) throws IOException { return EntityUtils.toByteArray(execute(Request.Get(url)).getEntity()); }
@Test public void shouldForwardRequestsUsingHttpClient() throws Exception { // given HttpClient httpClient = createHttpClient(); // when HttpPost request = new HttpPost( new URIBuilder() .setScheme("http") .setHost("localhost") .setPort(getServerPort()) .setPath(addContextToPath("test_headers_and_body")) .build() ); request.setEntity(new StringEntity("an_example_body")); HttpResponse response = httpClient.execute(request); // then assertEquals(HttpStatusCode.OK_200.code(), response.getStatusLine().getStatusCode()); assertEquals("an_example_body", new String(EntityUtils.toByteArray(response.getEntity()), UTF_8)); // and getMockServerClient().verify( request() .withMethod("POST") .withPath("/test_headers_and_body") .withBody("an_example_body"), exactly(1) ); }
@Test public void defaultHandlerFavicon() throws Exception { try (CloseableHttpClient hc = HttpClients.createMinimal()) { try (CloseableHttpResponse res = hc.execute( new HttpGet(server.uri("/default/favicon.ico")))) { assertThat(res.getStatusLine().toString()).isEqualTo("HTTP/1.1 200 OK"); assertThat(res.getFirstHeader(HttpHeaderNames.CONTENT_TYPE.toString()).getValue()) .startsWith("image/x-icon"); assertThat(EntityUtils.toByteArray(res.getEntity()).length) .isGreaterThan(0); } } }