org.apache.http.client.methods.CloseableHttpResponse.getStatusLine()方法的使用及代码示例

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

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

CloseableHttpResponse.getStatusLine介绍

暂无

代码示例

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

protected int getStatusCode(CloseableHttpResponse response) {
  return response.getStatusLine().getStatusCode();
}

代码示例来源: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: igniterealtime/Openfire

private void handleHTTPError(CloseableHttpResponse response) throws RemoteException {
  final StatusLine statusLine = response.getStatusLine();
  final int status = statusLine.getStatusCode();
  final String statusText = statusLine.getReasonPhrase();
  final String body = response.getEntity().toString();
  StringBuilder strBuf = new StringBuilder();
  strBuf.append("Crowd returned HTTP error code:").append(status);
  strBuf.append(" - ").append(statusText);
  if (StringUtils.isNotBlank(body)) {
    strBuf.append("\n").append(body);
  }
  
  throw new RemoteException(strBuf.toString());
}

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

@Test
  public void okNoHostName() throws Exception {
    try (CloseableHttpClient hc = HttpClients.createMinimal()) {
      try (CloseableHttpResponse res = hc.execute(new HttpGet(server.uri("/some-webapp-nohostname/")))) {
        assertThat(res.getStatusLine().toString()).isEqualTo("HTTP/1.1 200 OK");
      }
    }
  }
}

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

public void testInsertSuccess() throws IOException, URISyntaxException {
 setup(SalesforceRestWriter.Operation.INSERT_ONLY_NOT_EXIST);
 CloseableHttpResponse response = mock(CloseableHttpResponse.class);
 StatusLine statusLine = mock(StatusLine.class);
 when(client.execute(any(HttpUriRequest.class))).thenReturn(response);
 when(response.getStatusLine()).thenReturn(statusLine);
 when(statusLine.getStatusCode()).thenReturn(200);
 RestEntry<JsonObject> restEntry = new RestEntry<JsonObject>("test", new JsonObject());
 Optional<HttpUriRequest> request = writer.onNewRecord(restEntry);
 Assert.assertTrue(request.isPresent(), "No HttpUriRequest from onNewRecord");
 Assert.assertEquals("POST", request.get().getMethod());
 writer = spy(writer);
 writer.write(restEntry);
 verify(writer, times(1)).writeImpl(restEntry);
 verify(writer, times(1)).onNewRecord(restEntry);
 verify(writer, times(1)).sendRequest(any(HttpUriRequest.class));
 verify(client, times(1)).execute(any(HttpUriRequest.class));
 verify(writer, times(1)).waitForResponse(any(ListenableFuture.class));
 verify(writer, times(1)).processResponse(any(CloseableHttpResponse.class));
 verify(writer, never()).onConnect(any(URI.class));
}

代码示例来源: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: line/armeria

@Test
public void testMethodNotAllowed() throws Exception {
  try (CloseableHttpClient hc = HttpClients.createMinimal()) {
    final HttpPost req = new HttpPost(specificationUri());
    try (CloseableHttpResponse res = hc.execute(req)) {
      assertThat(res.getStatusLine().toString()).isEqualTo("HTTP/1.1 405 Method Not Allowed");
    }
  }
}

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

CloseableHttpResponse response = null;
try {
  response = httpclient.execute(httpGet);
  System.out.println(response.getStatusLine());
  HttpEntity entity = response.getEntity();
  EntityUtils.consume(entity);
}
finally {
  if (response != null) {
    response.close();
  }
}

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

@Test
public void shouldErrorOutIfServerRejectTheRequest() throws Exception {
  final ArgumentCaptor<HttpRequestBase> argumentCaptor = ArgumentCaptor.forClass(HttpRequestBase.class);
  final CloseableHttpResponse httpResponse = mock(CloseableHttpResponse.class);
  when(agentRegistry.uuid()).thenReturn("agent-uuid");
  when(httpClient.execute(any(HttpRequestBase.class))).thenReturn(httpResponse);
  when(httpResponse.getEntity()).thenReturn(new StringEntity("A token has already been issued for this agent."));
  when(httpResponse.getStatusLine()).thenReturn(new BasicStatusLine(new ProtocolVersion("https", 1, 2), SC_UNPROCESSABLE_ENTITY, null));
  thrown.expect(RuntimeException.class);
  thrown.expectMessage("A token has already been issued for this agent.");
  tokenRequester.getToken();
}

代码示例来源:origin: spotify/helios

@Override
 public Object call() {
  try {
   // While MasterService will start listening for http requests on the main and admin ports
   // as soon as it is started (without waiting for ZK to be available), the Healthcheck
   // registered for Zookeeper connectivity will cause the HealthcheckServlet to not return
   // 200 OK until ZK is connected to (and even better, until *everything* is healthy).
   final HttpGet request = new HttpGet(masterAdminEndpoint + "/healthcheck");
   try (CloseableHttpResponse response = httpClient.execute(request)) {
    final int status = response.getStatusLine().getStatusCode();
    log.debug("waitForMasterToBeFullyUp: healthcheck endpoint returned {}", status);
    return status == HttpStatus.SC_OK;
   }
  } catch (Exception e) {
   return null;
  }
 }
});

代码示例来源: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: loklak/loklak_server

public int getStatusCode() {
  return this.httpResponse.getStatusLine().getStatusCode();
}

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

@Test
public void ok() throws Exception {
  try (CloseableHttpClient hc = HttpClients.createMinimal()) {
    try (CloseableHttpResponse res = hc.execute(new HttpGet(server.uri("/some-webapp/")))) {
      assertThat(res.getStatusLine().toString()).isEqualTo("HTTP/1.1 200 OK");
    }
  }
}

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

public void testUpsertSuccess() throws IOException, URISyntaxException {
 setup(SalesforceRestWriter.Operation.UPSERT);
 CloseableHttpResponse response = mock(CloseableHttpResponse.class);
 StatusLine statusLine = mock(StatusLine.class);
 when(client.execute(any(HttpUriRequest.class))).thenReturn(response);
 when(response.getStatusLine()).thenReturn(statusLine);
 when(statusLine.getStatusCode()).thenReturn(200);
 RestEntry<JsonObject> restEntry = new RestEntry<JsonObject>("test", new JsonObject());
 Optional<HttpUriRequest> request = writer.onNewRecord(restEntry);
 Assert.assertTrue(request.isPresent(), "No HttpUriRequest from onNewRecord");
 Assert.assertEquals("PATCH", request.get().getMethod());
 writer = spy(writer);
 writer.write(restEntry);
 verify(writer, times(1)).writeImpl(restEntry);
 verify(writer, times(1)).onNewRecord(restEntry);
 verify(writer, times(1)).sendRequest(any(HttpUriRequest.class));
 verify(client, times(1)).execute(any(HttpUriRequest.class));
 verify(writer, times(1)).waitForResponse(any(ListenableFuture.class));
 verify(writer, times(1)).processResponse(any(CloseableHttpResponse.class));
 verify(writer, never()).onConnect(any(URI.class));
}

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

@Test
public void echoPostWithEmptyBody() throws Exception {
  try (CloseableHttpClient hc = HttpClients.createMinimal()) {
    final HttpPost post = new HttpPost(server().uri("/jsp/echo_post.jsp"));
    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></p>" +
          "</body></html>");
    }
  }
}

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

@Test
public void testMethodNotAllowed() throws Exception {
  try (CloseableHttpClient hc = HttpClients.createMinimal()) {
    final HttpPost req = new HttpPost(specificationUri());
    try (CloseableHttpResponse res = hc.execute(req)) {
      assertThat(res.getStatusLine().toString()).isEqualTo("HTTP/1.1 405 Method Not Allowed");
    }
  }
}

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

@Test
public void shouldGetTokenFromServer() throws Exception {
  final ArgumentCaptor<HttpRequestBase> argumentCaptor = ArgumentCaptor.forClass(HttpRequestBase.class);
  final CloseableHttpResponse httpResponse = mock(CloseableHttpResponse.class);
  when(agentRegistry.uuid()).thenReturn("agent-uuid");
  when(httpClient.execute(any(HttpRequestBase.class))).thenReturn(httpResponse);
  when(httpResponse.getEntity()).thenReturn(new StringEntity("token-from-server"));
  when(httpResponse.getStatusLine()).thenReturn(new BasicStatusLine(new ProtocolVersion("https", 1, 2), SC_OK, null));
  final String token = tokenRequester.getToken();
  verify(httpClient).execute(argumentCaptor.capture());
  final HttpRequestBase requestBase = argumentCaptor.getValue();
  final List<NameValuePair> nameValuePairs = URLEncodedUtils.parse(requestBase.getURI(), StandardCharsets.UTF_8.name());
  assertThat(token, is("token-from-server"));
  assertThat(findParam(nameValuePairs, "uuid").getValue(), is("agent-uuid"));
}

代码示例来源: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: apache/incubator-gobblin

private void processSingleRequestResponse(CloseableHttpResponse response) throws IOException,
  UnexpectedResponseException {
 int statusCode = response.getStatusLine().getStatusCode();
 if (statusCode < 400) {
  return;
 }
 String entityStr = EntityUtils.toString(response.getEntity());
 if (statusCode == 400
   && Operation.INSERT_ONLY_NOT_EXIST.equals(operation)
   && entityStr != null) { //Ignore if it's duplicate entry error code
  JsonArray jsonArray = new JsonParser().parse(entityStr).getAsJsonArray();
  JsonObject jsonObject = jsonArray.get(0).getAsJsonObject();
  if (isDuplicate(jsonObject, statusCode)) {
   return;
  }
 }
 throw new RuntimeException("Failed due to " + entityStr + " (Detail: "
   + ToStringBuilder.reflectionToString(response, ToStringStyle.SHORT_PREFIX_STYLE) + " )");
}

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

public CloseableHttpResponse execute(HttpRequestBase httpMethod) throws IOException {
  GoAgentServerHttpClient client = httpClientFactory.httpClient();
  CloseableHttpResponse response = client.execute(httpMethod);
  LOGGER.info("Got back {} from server", response.getStatusLine().getStatusCode());
  return response;
}

相关文章