org.apache.http.client.methods.CloseableHttpResponse类的使用及代码示例

x33g5p2x  于2022-01-17 转载在 其他  
字(13.8k)|赞(0)|评价(0)|浏览(139)

本文整理了Java中org.apache.http.client.methods.CloseableHttpResponse类的一些代码示例,展示了CloseableHttpResponse类的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。CloseableHttpResponse类的具体详情如下:
包路径:org.apache.http.client.methods.CloseableHttpResponse
类名称:CloseableHttpResponse

CloseableHttpResponse介绍

[英]Extended version of the HttpResponse interface that also extends Closeable.
[中]HttpResponse接口的扩展版本,该接口还扩展了Closeable。

代码示例

代码示例来源:origin: apache/incubator-gobblin

/**
 * Default implementation where any status code equal to or greater than 400 is regarded as a failure.
 * {@inheritDoc}
 * @see org.apache.gobblin.writer.http.HttpWriterDecoration#processResponse(org.apache.http.HttpResponse)
 */
@Override
public void processResponse(CloseableHttpResponse response) throws IOException, UnexpectedResponseException {
 if (response.getStatusLine().getStatusCode() >= 400) {
  if (response.getEntity() != null) {
   throw new RuntimeException("Failed. " + EntityUtils.toString(response.getEntity())
                + " , response: " + ToStringBuilder.reflectionToString(response, ToStringStyle.SHORT_PREFIX_STYLE));
  }
  throw new RuntimeException("Failed. Response: " + ToStringBuilder.reflectionToString(response, ToStringStyle.SHORT_PREFIX_STYLE));
 }
}

代码示例来源:origin: alibaba/canal

.setSocketTimeout(timeout)
  .build();
HttpGet httpGet = new HttpGet(uri);
HttpClientContext context = HttpClientContext.create();
context.setRequestConfig(config);
CloseableHttpResponse response = httpclient.execute(httpGet, context);
try {
  int statusCode = response.getStatusLine().getStatusCode();
  long end = System.currentTimeMillis();
  long cost = end - start;
    return EntityUtils.toByteArray(response.getEntity());
  } else {
    String errorMsg = EntityUtils.toString(response.getEntity());
    throw new RuntimeException("requestGet remote error, url=" + uri.toString() + ", code=" + statusCode
                  + ", error msg=" + errorMsg);
  response.close();
  httpGet.releaseConnection();

代码示例来源:origin: line/armeria

@Test
public void echoPost() throws Exception {
  try (CloseableHttpClient hc = HttpClients.createMinimal()) {
    final HttpPost post = new HttpPost(server().uri("/jsp/echo_post.jsp"));
    post.setEntity(new StringEntity("test"));
    try (CloseableHttpResponse res = hc.execute(post)) {
      assertThat(res.getStatusLine().toString()).isEqualTo("HTTP/1.1 200 OK");
      assertThat(res.getFirstHeader(HttpHeaderNames.CONTENT_TYPE.toString()).getValue())
          .startsWith("text/html");
      final String actualContent = CR_OR_LF.matcher(EntityUtils.toString(res.getEntity()))
                         .replaceAll("");
      assertThat(actualContent).isEqualTo(
          "<html><body>" +
          "<p>Check request body</p>" +
          "<p>test</p>" +
          "</body></html>");
    }
  }
}

代码示例来源:origin: liyiorg/weixin-popular

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;
}

代码示例来源:origin: stackoverflow.com

SSLContextBuilder builder = new SSLContextBuilder();
 builder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
 SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
     builder.build());
 CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(
     sslsf).build();
 HttpGet httpGet = new HttpGet("https://some-server");
 CloseableHttpResponse response = httpclient.execute(httpGet);
 try {
   System.out.println(response.getStatusLine());
   HttpEntity entity = response.getEntity();
   EntityUtils.consume(entity);
 }
 finally {
   response.close();
 }

代码示例来源:origin: brianfrankcooper/YCSB

timer.start();
int responseCode = 200;
HttpGet request = new HttpGet(endpoint);
for (int i = 0; i < headers.length; i = i + 2) {
 request.setHeader(headers[i], headers[i + 1]);
CloseableHttpResponse response = client.execute(request);
responseCode = response.getStatusLine().getStatusCode();
HttpEntity responseEntity = response.getEntity();
 InputStream stream = responseEntity.getContent();
   EntityUtils.consumeQuietly(responseEntity);
   response.close();
   client.close();
   throw new TimeoutException();
EntityUtils.consumeQuietly(responseEntity);
response.close();
client.close();
return responseCode;

代码示例来源:origin: alibaba/canal

parameters.add(nameValuePair);
httpPost.setEntity(new UrlEncodedFormEntity(parameters, Charset.forName("UTF-8")));
HttpClientContext context = HttpClientContext.create();
context.setRequestConfig(config);
context.setCookieStore(cookieStore);
response = httpclient.execute(httpPost, context);
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode == HttpStatus.SC_OK) {
  long end = System.currentTimeMillis();
  long cost = end - start;
  printCurlRequest(url, cookieStore, params, cost);
  return EntityUtils.toString(response.getEntity());
} else {
  long end = System.currentTimeMillis();
  String curlRequest = getCurlRequest(url, cookieStore, params, cost);
  throw new RuntimeException("requestPost remote error, request : " + curlRequest + ", statusCode="
                + statusCode + ";" + EntityUtils.toString(response.getEntity()));
if (response != null) {
  try {
    response.close();
  } catch (IOException e) {
  httpPost.releaseConnection();

代码示例来源:origin: medcl/elasticsearch-analysis-ik

CloseableHttpResponse response;
BufferedReader in;
HttpGet get = new HttpGet(location);
get.setConfig(rc);
try {
  response = httpclient.execute(get);
  if (response.getStatusLine().getStatusCode() == 200) {
    if (response.getEntity().getContentType().getValue().contains("charset=")) {
      String contentType = response.getEntity().getContentType().getValue();
      charset = contentType.substring(contentType.lastIndexOf("=") + 1);
    in = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), charset));
    String line;
    while ((line = in.readLine()) != null) {
    response.close();
    return buffer;
  response.close();
} catch (ClientProtocolException e) {
  logger.error("getRemoteWords {} error", e, location);

代码示例来源:origin: kairosdb/kairosdb

HttpPost post = new HttpPost(url + "/api/v1/datapoints");
post.setHeader("Content-Type", "application/gzip");
post.setEntity(new InputStreamEntity(zipStream, zipFile.length()));
try (CloseableHttpResponse response = client.execute(post))
  if (response.getStatusLine().getStatusCode() == 204)
    response.getEntity().writeTo(body);
    logger.error("Unable to send file " + zipFile + ": " + response.getStatusLine() +
        " - " + body.toString("UTF-8"));

代码示例来源:origin: dropwizard/dropwizard

/**
 * {@inheritDoc}
 */
@Override
public ClientResponse apply(ClientRequest jerseyRequest) {
  try {
    final HttpUriRequest apacheRequest = buildApacheRequest(jerseyRequest);
    final CloseableHttpResponse apacheResponse = client.execute(apacheRequest);
    final StatusLine statusLine = apacheResponse.getStatusLine();
    final String reasonPhrase = Strings.nullToEmpty(statusLine.getReasonPhrase());
    final Response.StatusType status = Statuses.from(statusLine.getStatusCode(), reasonPhrase);
    final ClientResponse jerseyResponse = new ClientResponse(status, jerseyRequest);
    for (Header header : apacheResponse.getAllHeaders()) {
      jerseyResponse.getHeaders().computeIfAbsent(header.getName(), k -> new ArrayList<>())
        .add(header.getValue());
    }
    final HttpEntity httpEntity = apacheResponse.getEntity();
    jerseyResponse.setEntityStream(httpEntity != null ? httpEntity.getContent() :
        new ByteArrayInputStream(new byte[0]));
    return jerseyResponse;
  } catch (Exception e) {
    throw new ProcessingException(e);
  }
}

代码示例来源:origin: alibaba/jstorm

private boolean httpPost(String url, String msg) {
  boolean ret = false;
  CloseableHttpClient httpClient = HttpClientBuilder.create().build();
  CloseableHttpResponse response = null;
  try {
    HttpPost request = new HttpPost(url);
    List<NameValuePair> nvps = new ArrayList<>();
    nvps.add(new BasicNameValuePair("name", monitorName));
    nvps.add(new BasicNameValuePair("msg", msg));
    request.setEntity(new UrlEncodedFormEntity(nvps));
    response = httpClient.execute(request);
    HttpEntity entity = response.getEntity();
    if (entity != null) {
      LOG.info(EntityUtils.toString(entity));
    }
    EntityUtils.consume(entity);
    ret = true;
  } catch (Exception e) {
    LOG.error("Exception when sending http request to ali monitor", e);
  } finally {
    try {
      if (response != null)
        response.close();
      httpClient.close();
    } catch (Exception e) {
      LOG.error("Exception when closing httpclient", e);
    }
  }
  return ret;
}

代码示例来源:origin: apache/nifi

private String execute(final HttpGet get) throws IOException {
  final CloseableHttpClient httpClient = getHttpClient();
  if (logger.isTraceEnabled()) {
    Arrays.stream(get.getAllHeaders()).forEach(h -> logger.debug("REQ| {}", h));
  }
  try (final CloseableHttpResponse response = httpClient.execute(get)) {
    if (logger.isTraceEnabled()) {
      Arrays.stream(response.getAllHeaders()).forEach(h -> logger.debug("RES| {}", h));
    }
    final StatusLine statusLine = response.getStatusLine();
    final int statusCode = statusLine.getStatusCode();
    if (RESPONSE_CODE_OK != statusCode) {
      throw new HttpGetFailedException(statusCode, statusLine.getReasonPhrase(), null);
    }
    final HttpEntity entity = response.getEntity();
    final String responseMessage = EntityUtils.toString(entity);
    return responseMessage;
  }
}

代码示例来源:origin: spring-projects/spring-data-examples

private void checkServerRunning() {
  try (CloseableHttpClient client = HttpClientBuilder.create().build()) {
    CloseableHttpResponse response = client.execute(new HttpGet(baseUrl + PING_PATH));
    if (response != null && response.getStatusLine() != null) {
      Assume.assumeThat(response.getStatusLine().getStatusCode(), Is.is(200));
    }
  } catch (IOException e) {
    throw new AssumptionViolatedException("SolrServer does not seem to be running", e);
  }
}

代码示例来源:origin: alibaba/jstorm

private boolean httpGet(StringBuilder postAddr) {
  boolean ret = false;
  CloseableHttpClient httpClient = HttpClientBuilder.create().build();
  CloseableHttpResponse response = null;
  try {
    HttpGet request = new HttpGet(postAddr.toString());
    response = httpClient.execute(request);
    HttpEntity entity = response.getEntity();
    if (entity != null) {
      LOG.info(EntityUtils.toString(entity));
    }
    EntityUtils.consume(entity);
    ret = true;
  } catch (Exception e) {
    LOG.error("Exception when sending http request to ali monitor", e);
  } finally {
    try {
      if (response != null)
        response.close();
      httpClient.close();
    } catch (Exception e) {
      LOG.error("Exception when closing httpclient", e);
    }
  }
  return ret;
}

代码示例来源:origin: floragunncom/search-guard

public HttpResponse(CloseableHttpResponse inner) throws IllegalStateException, IOException {
  super();
  this.inner = inner;
  final HttpEntity entity = inner.getEntity();
  if(entity == null) { //head request does not have a entity
    this.body = "";
  } else {
    this.body = IOUtils.toString(entity.getContent(), StandardCharsets.UTF_8);
  }
  this.header = inner.getAllHeaders();
  this.statusCode = inner.getStatusLine().getStatusCode();
  this.statusReason = inner.getStatusLine().getReasonPhrase();
  inner.close();
}

代码示例来源:origin: knightliao/disconf

httpclientResponse = httpclient.execute(request);
  for (Header header : httpclientResponse.getAllHeaders()) {
    LOGGER.debug("response header: {}\t{}", header.getName(), header.getValue());
int statusCode = httpclientResponse.getStatusLine().getStatusCode();
  HttpEntity requestEntity = ((HttpEntityEnclosingRequestBase) request).getEntity();
  if (requestEntity != null) {
    requestBody = EntityUtils.toString(requestEntity);
HttpEntity entity = httpclientResponse.getEntity();
if (entity != null && responseHandler != null) {
  return responseHandler.handleResponse(requestBody, entity);
if (httpclientResponse != null) {
  try {
    httpclientResponse.close();
  } catch (IOException e) {

代码示例来源:origin: apache/incubator-pinot

private SimpleHttpResponse sendRequest(HttpUriRequest request)
  throws IOException, HttpErrorStatusException {
 try (CloseableHttpResponse response = _httpClient.execute(request)) {
  String controllerHost = null;
  String controllerVersion = null;
  if (response.containsHeader(CommonConstants.Controller.HOST_HTTP_HEADER)) {
   controllerHost = response.getFirstHeader(CommonConstants.Controller.HOST_HTTP_HEADER).getValue();
   controllerVersion = response.getFirstHeader(CommonConstants.Controller.VERSION_HTTP_HEADER).getValue();
  }
  if (controllerHost != null) {
   LOGGER.info(String
     .format("Sending request: %s to controller: %s, version: %s", request.getURI(), controllerHost,
       controllerVersion));
  }
  int statusCode = response.getStatusLine().getStatusCode();
  if (statusCode >= 300) {
   throw new HttpErrorStatusException(getErrorMessage(request, response), statusCode);
  }
  return new SimpleHttpResponse(statusCode, EntityUtils.toString(response.getEntity()));
 }
}

代码示例来源:origin: stackoverflow.com

CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPost uploadFile = new HttpPost("...");
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.addTextBody("field1", "yes", ContentType.TEXT_PLAIN);

// This attaches the file to the POST:
File f = new File("[/path/to/upload]");
builder.addBinaryBody(
  "file",
  new FileInputStream(f),
  ContentType.APPLICATION_OCTET_STREAM,
  f.getName()
);

HttpEntity multipart = builder.build();
uploadFile.setEntity(multipart);
CloseableHttpResponse response = httpClient.execute(uploadFile);
HttpEntity responseEntity = response.getEntity();

代码示例来源:origin: apache/hive

try {
 httpclient = HttpClients.createDefault();
 HttpGet httpGet = new HttpGet("http://localhost:"+webUIPort+"/conf");
 CloseableHttpResponse response1 = httpclient.execute(httpGet);
  HttpEntity entity1 = response1.getEntity();
  BufferedReader br = new BufferedReader(new InputStreamReader(entity1.getContent()));
  String line;
  while ((line = br.readLine())!= null) {
  EntityUtils.consume(entity1);
 } finally {
  response1.close();
  httpclient.close();

代码示例来源:origin: cloudfoundry/uaa

@Test
public void testUnauthenticatedRedirect() throws Exception {
  String location = serverRunning.getBaseUrl() + "/";
  HttpGet httpget = new HttpGet(location);
  httpget.setConfig(
    RequestConfig.custom().setRedirectsEnabled(false).build()
  );
  CloseableHttpResponse response = httpclient.execute(httpget);
  assertEquals(FOUND.value(), response.getStatusLine().getStatusCode());
  location = response.getFirstHeader("Location").getValue();
  response.close();
  httpget.completed();
  assertTrue(location.contains("/login"));
}

相关文章