类org.apache.http.StatusLine源码实例Demo

下面列出了怎么用org.apache.http.StatusLine的API类实例代码及写法,或者点击链接到github查看源代码。

源代码1 项目: curly   文件: ActionResult.java
public void processHttpResponse(CloseableHttpResponse httpResponse, ResultType resultType) throws IOException {
    StatusLine status = httpResponse.getStatusLine();
    String statusKey = COMPLETED_SUCCESSFUL;
    boolean successfulResponseCode = false;
    if (status.getStatusCode() >= 200 && status.getStatusCode() < 400) {
        successfulResponseCode = true;
    } else {
        statusKey = COMPLETED_UNSUCCESSFUL;
    }
    String resultMessage = "";
    if (resultType == ResultType.HTML) {
        ParsedResponseMessage message = extractHtmlMessage(httpResponse).orElse(UNKNOWN_RESPONSE);
        if (message.type == RESULT_TYPE.FAIL) {
            successfulResponseCode = false;
            statusKey = COMPLETED_UNSUCCESSFUL;
        }
        resultMessage = status.getReasonPhrase() + " / " + message.message;
    } else {
        resultMessage = status.getReasonPhrase();
    }
    percentSuccess().unbind();
    percentSuccess().set(successfulResponseCode ? 1 : 0);
    invalidateBindings();
    setStatus(statusKey, status.getStatusCode(), resultMessage);
}
 
源代码2 项目: vividus   文件: HttpClientTests.java
@Test
void testDoHttpHead() throws Exception
{
    CloseableHttpResponse closeableHttpResponse = mock(CloseableHttpResponse.class);
    HttpContext context = null;
    when(closeableHttpResponse.getEntity()).thenReturn(null);
    StatusLine statusLine = mock(StatusLine.class);
    int statusCode = HttpStatus.SC_MOVED_PERMANENTLY;
    Header[] headers = { header };
    when(closeableHttpResponse.getAllHeaders()).thenReturn(headers);
    when(statusLine.getStatusCode()).thenReturn(statusCode);
    when(closeableHttpResponse.getStatusLine()).thenReturn(statusLine);
    when(closeableHttpClient.execute(isA(HttpHead.class), eq(context)))
            .thenAnswer(getAnswerWithSleep(closeableHttpResponse));
    HttpResponse httpResponse = httpClient.doHttpHead(URI_TO_GO);
    assertEquals(HEAD, httpResponse.getMethod());
    assertEquals(URI_TO_GO, httpResponse.getFrom());
    assertEquals(statusCode, httpResponse.getStatusCode());
    assertThat(httpResponse.getResponseTimeInMs(), greaterThan(0L));
    assertThat(httpResponse.getResponseHeaders(), is(equalTo(headers)));
}
 
@Override
public void sendResponseMessage(HttpResponse response) throws IOException {
    // do not process if request has been cancelled
    if (!Thread.currentThread().isInterrupted()) {
        StatusLine status = response.getStatusLine();
        byte[] responseBody;
        responseBody = getResponseData(response.getEntity());
        // additional cancellation check as getResponseData() can take non-zero time to process
        if (!Thread.currentThread().isInterrupted()) {
            if (status.getStatusCode() >= 300) {
                sendFailureMessage(status.getStatusCode(), response.getAllHeaders(), responseBody, new HttpResponseException(status.getStatusCode(), status.getReasonPhrase()));
            } else {
                sendSuccessMessage(status.getStatusCode(), response.getAllHeaders(), responseBody);
            }
        }
    }
}
 
@Override
public void sendResponseMessage(HttpResponse response) throws IOException {
    // do not process if request has been cancelled
    if (!Thread.currentThread().isInterrupted()) {
        StatusLine status = response.getStatusLine();
        byte[] responseBody;
        responseBody = getResponseData(response.getEntity());
        // additional cancellation check as getResponseData() can take non-zero time to process
        if (!Thread.currentThread().isInterrupted()) {
            if (status.getStatusCode() >= 300) {
                sendFailureMessage(status.getStatusCode(), response.getAllHeaders(), responseBody, new HttpResponseException(status.getStatusCode(), status.getReasonPhrase()));
            } else {
                sendSuccessMessage(status.getStatusCode(), response.getAllHeaders(), responseBody);
            }
        }
    }
}
 
源代码5 项目: helix   文件: TestCustomRestClient.java
@Test
public void testGetInstanceStoppableCheck() throws IOException {
  MockCustomRestClient customRestClient = new MockCustomRestClient(_httpClient);
  String jsonResponse = "{\n" + "   \"check1\": \"false\",\n" + "   \"check2\": \"true\"\n" + "}";

  HttpResponse httpResponse = mock(HttpResponse.class);
  StatusLine statusLine = mock(StatusLine.class);

  when(statusLine.getStatusCode()).thenReturn(HttpStatus.SC_OK);
  when(httpResponse.getStatusLine()).thenReturn(statusLine);
  customRestClient.setJsonResponse(jsonResponse);
  when(_httpClient.execute(any(HttpPost.class))).thenReturn(httpResponse);

  Map<String, Boolean> healthCheck =
      customRestClient.getInstanceStoppableCheck(HTTP_LOCALHOST, Collections.emptyMap());
  Assert.assertFalse(healthCheck.get("check1"));
  Assert.assertTrue(healthCheck.get("check2"));
}
 
源代码6 项目: aem-core-cif-components   文件: Utils.java
/**
 * This method prepares the mock http response with either the content of the <code>filename</code>
 * or the provided <code>content</code> String.<br>
 * <br>
 * <b>Important</b>: because of the way the content of an HTTP response is consumed, this method MUST be called each time
 * the client is called.
 *
 * @param filename The file to use for the json response.
 * @param httpClient The HTTP client for which we want to mock responses.
 * @param httpCode The http code that the mocked response will return.
 * @param startsWith When set, the body of the GraphQL POST request must start with that String.
 *
 * @return The JSON content of that file.
 *
 * @throws IOException
 */
public static String setupHttpResponse(String filename, HttpClient httpClient, int httpCode, String startsWith) throws IOException {
    String json = IOUtils.toString(Utils.class.getClassLoader().getResourceAsStream(filename), StandardCharsets.UTF_8);

    HttpEntity mockedHttpEntity = Mockito.mock(HttpEntity.class);
    HttpResponse mockedHttpResponse = Mockito.mock(HttpResponse.class);
    StatusLine mockedStatusLine = Mockito.mock(StatusLine.class);

    byte[] bytes = json.getBytes(StandardCharsets.UTF_8);
    Mockito.when(mockedHttpEntity.getContent()).thenReturn(new ByteArrayInputStream(bytes));
    Mockito.when(mockedHttpEntity.getContentLength()).thenReturn(new Long(bytes.length));

    Mockito.when(mockedHttpResponse.getEntity()).thenReturn(mockedHttpEntity);

    if (startsWith != null) {
        GraphqlQueryMatcher matcher = new GraphqlQueryMatcher(startsWith);
        Mockito.when(httpClient.execute(Mockito.argThat(matcher))).thenReturn(mockedHttpResponse);
    } else {
        Mockito.when(httpClient.execute((HttpUriRequest) Mockito.any())).thenReturn(mockedHttpResponse);
    }

    Mockito.when(mockedStatusLine.getStatusCode()).thenReturn(httpCode);
    Mockito.when(mockedHttpResponse.getStatusLine()).thenReturn(mockedStatusLine);

    return json;
}
 
源代码7 项目: junit-servers   文件: ApacheHttpResponseBuilder.java
@Override
public HttpResponse build() {
	ProtocolVersion protocolVersion = new ProtocolVersion("HTTP", 1, 1);
	StatusLine statusLine = new BasicStatusLine(protocolVersion, status, "");
	HttpResponse response = new BasicHttpResponse(statusLine);

	InputStream is = new ByteArrayInputStream(body.getBytes(StandardCharsets.UTF_8));
	BasicHttpEntity entity = new BasicHttpEntity();
	entity.setContent(is);
	response.setEntity(entity);

	for (Map.Entry<String, List<String>> header : headers.entrySet()) {
		for (String value : header.getValue()) {
			response.addHeader(header.getKey(), value);
		}
	}

	return response;
}
 
源代码8 项目: vespa   文件: StateV1HealthUpdaterTest.java
private ServiceStatusInfo getServiceStatusInfoFromJsonResponse(String content)
        throws IOException {
    CloseableHttpClient client = mock(CloseableHttpClient.class);

    CloseableHttpResponse response = mock(CloseableHttpResponse.class);
    when(client.execute(any())).thenReturn(response);

    StatusLine statusLine = mock(StatusLine.class);
    when(response.getStatusLine()).thenReturn(statusLine);

    when(statusLine.getStatusCode()).thenReturn(200);

    HttpEntity httpEntity = mock(HttpEntity.class);
    when(response.getEntity()).thenReturn(httpEntity);

    try (StateV1HealthUpdater updater = makeUpdater(client, entry -> content)) {
        when(httpEntity.getContentLength()).thenReturn((long) content.length());
        updater.run();
        return updater.getServiceStatusInfo();
    }
}
 
@Override
public void sendResponseMessage(HttpResponse response) throws IOException {
    // do not process if request has been cancelled
    if (!Thread.currentThread().isInterrupted()) {
        StatusLine status = response.getStatusLine();
        byte[] responseBody;
        responseBody = getResponseData(response.getEntity());
        // additional cancellation check as getResponseData() can take non-zero time to process
        if (!Thread.currentThread().isInterrupted()) {
            if (status.getStatusCode() >= 300) {
                sendFailureMessage(status.getStatusCode(), response.getAllHeaders(), responseBody, new HttpResponseException(status.getStatusCode(), status.getReasonPhrase()));
            } else {
                sendSuccessMessage(status.getStatusCode(), response.getAllHeaders(), responseBody);
            }
        }
    }
}
 
源代码10 项目: bullet-core   文件: RESTQueryPublisherTest.java
@Test
public void testSendResultUrlPutInMetadataAckPreserved() throws Exception {
    CloseableHttpClient mockClient = mock(CloseableHttpClient.class);
    CloseableHttpResponse mockResponse = mock(CloseableHttpResponse.class);
    StatusLine mockStatusLine = mock(StatusLine.class);
    doReturn(200).when(mockStatusLine).getStatusCode();
    doReturn(mockStatusLine).when(mockResponse).getStatusLine();
    doReturn(mockResponse).when(mockClient).execute(any());
    RESTQueryPublisher publisher = new RESTQueryPublisher(mockClient, "my/custom/query/url", "my/custom/url", 5000);
    PubSubMessage actual = publisher.send(new PubSubMessage("foo", CONTENT, Metadata.Signal.ACKNOWLEDGE));

    Assert.assertTrue(actual.getMetadata() instanceof RESTMetadata);
    RESTMetadata actualMeta = (RESTMetadata) actual.getMetadata();
    Assert.assertEquals(actualMeta.getUrl(), "my/custom/url");

    ArgumentCaptor<HttpPost> argumentCaptor = ArgumentCaptor.forClass(HttpPost.class);
    verify(mockClient).execute(argumentCaptor.capture());
    HttpPost post = argumentCaptor.getValue();
    String actualMessage = EntityUtils.toString(post.getEntity(), RESTPubSub.UTF_8);
    String expectedMessage = "{'id':'foo','content':[98,97,114],'metadata':{'url':'my/custom/url','signal':ACKNOWLEDGE,'content':null,'created':" + actual.getMetadata().getCreated() + "}}";
    String actualHeader = post.getHeaders(RESTPublisher.CONTENT_TYPE)[0].getValue();
    String expectedHeader = RESTPublisher.APPLICATION_JSON;
    assertJSONEquals(actualMessage, expectedMessage);
    Assert.assertEquals(expectedHeader, actualHeader);
    Assert.assertEquals("my/custom/query/url", post.getURI().toString());
}
 
源代码11 项目: apm-agent-java   文件: FutureCallbackWrapper.java
private void finishSpan(@Nullable Exception e) {
    // start by reading the volatile field
    final Span localSpan = span;
    try {
        if (context != null) {
            Object responseObject = context.getAttribute(HttpCoreContext.HTTP_RESPONSE);
            if (responseObject instanceof HttpResponse) {
                StatusLine statusLine = ((HttpResponse) responseObject).getStatusLine();
                if (statusLine != null) {
                    span.getContext().getHttp().withStatusCode(statusLine.getStatusCode());
                }
            }
        }
        localSpan.captureException(e);
    } finally {
        localSpan.end();
    }
}
 
源代码12 项目: PYX-Reloaded   文件: CardcastService.java
@Nullable
private String getUrlContent(String urlStr) throws IOException {
    HttpResponse resp = client.execute(new HttpGet(urlStr));

    StatusLine sl = resp.getStatusLine();
    if (sl.getStatusCode() != HttpStatus.SC_OK) {
        LOG.error(String.format("Got HTTP response code %s from Cardcast for %s", sl, urlStr));
        return null;
    }

    HttpEntity entity = resp.getEntity();
    String contentType = entity.getContentType().getValue();
    if (!Objects.equals(contentType, "application/json")) {
        LOG.error(String.format("Got content-type %s from Cardcast for %s", contentType, urlStr));
        return null;
    }

    return EntityUtils.toString(entity);
}
 
源代码13 项目: pushfish-android   文件: HttpUtil.java
public static String Delete(String endpoint, Map<String, String> data) throws IOException {
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    try {
        HttpDelete httpDelete = new HttpDelete(endpoint + "?" + urlencode(data));
        httpDelete.setHeader("user-agent", "Pushfish-android");
        HttpResponse response = (new DefaultHttpClient()).execute(httpDelete);
        StatusLine statusLine = response.getStatusLine();
        if (statusLine.getStatusCode() != HttpStatus.SC_OK) {
            throw new IOException("Get failed with error code " + statusLine.getStatusCode());
        }
        response.getEntity().writeTo(out);
        return out.toString();
    } finally {
        out.close();
    }
}
 
源代码14 项目: caravan   文件: HttpRequestException.java
public HttpRequestException(CloseableHttpResponse response) {
    super(toErrorMessage(response));

    StatusLine statusLine = response.getStatusLine();
    if (statusLine == null)
        return;

    _statusCode = statusLine.getStatusCode();
    _reasonPhrase = statusLine.getReasonPhrase();
    _protocolVersion = statusLine.getProtocolVersion();
    _responseHeaders = response.getAllHeaders();

    HttpEntity entity = response.getEntity();
    if (entity == null)
        return;

    try (InputStream is = entity.getContent();) {
        _responseBody = EntityUtils.toString(entity);
    } catch (Throwable ex) {

    }
}
 
源代码15 项目: sakai   文件: BitlyUrlService.java
/**
 * Makes a GET request to the given address. Any query string should be appended already.
 * @param address	the fully qualified URL to make the request to
 * @return
 */
private String doGet(String address){
	try {
		
		HttpClient httpclient = new DefaultHttpClient();
		HttpGet httpget = new HttpGet(address);
		HttpResponse response = httpclient.execute(httpget);
		
		//check reponse code
		StatusLine status = response.getStatusLine();
		if(status.getStatusCode() != 200) {
			log.error("Error shortening URL. Status: " + status.getStatusCode() + ", reason: " + status.getReasonPhrase());
			return null;
		}
		
		HttpEntity entity = response.getEntity();
		if (entity != null) {
		    return EntityUtils.toString(entity);
		}
		
	} catch (Exception e) {
		log.error(e.getClass() + ":" + e.getMessage());
	} 
	return null;
}
 
/**
 * handleExceptionStatusCode - throws the correct error for a status
 *
 * @param statusLine the status line we want to check
 * @throws BackOffException -- if we have a 503 exception
 * @throws IOException      - if we don't know what it is
 */
private static void handleExceptionalStatus(StatusLine statusLine,
                                            HttpResponse response)
                    throws IOException, IngestResponseException
{
  //if we have a 503 exception throw a backoff
  switch (statusLine.getStatusCode())
  {
    //If we have a 503, BACKOFF
    case HttpStatus.SC_SERVICE_UNAVAILABLE:
      LOGGER.warn("503 Status hit, backoff");
      throw new BackOffException();

      //We don't know how to respond now...
    default:
      LOGGER.error("Status code {} found in response from service",
                   statusLine.getStatusCode());
      String blob = EntityUtils.toString(response.getEntity());
      throw new IngestResponseException(statusLine.getStatusCode(),
                                        IngestResponseException
                                        .IngestExceptionBody.parseBody(blob));
  }

}
 
源代码17 项目: sherlock   文件: HttpServiceTest.java
@Test
public void testQueryDruidDatasourcesBadResponse() throws DruidException, IOException {
    mockGets();
    when(http.queryDruidDatasources(any(DruidCluster.class))).thenCallRealMethod();
    DruidCluster cluster = mock(DruidCluster.class);
    String url = "http://battlelog.battlefield.com/bf3/";
    when(cluster.getBrokerUrl()).thenReturn(url);
    StatusLine sl = mock(StatusLine.class);
    when(sl.getStatusCode()).thenReturn(500);
    when(res.getStatusLine()).thenReturn(sl);
    when(client.execute(any(HttpGet.class))).thenReturn(res);
    try {
        http.queryDruidDatasources(cluster);
    } catch (DruidException e) {
        assertEquals(e.getMessage(), "Get request to cluster datasources endpoint failed: 500");
        verify(get, times(1)).releaseConnection();
        return;
    }
    fail();
}
 
源代码18 项目: validatar   文件: JSON.java
/**
 * Makes the request and returns the String response using the given client, request and query.
 *
 * @param client The HttpClient to use.
 * @param request The HttpUriRequest to make.
 * @param query The Query object being run.
 * @return The String response of the call, null if exception (query is failed).
 */
String makeRequest(HttpClient client, HttpUriRequest request, Query query) {
    try {
        log.info("{}ing to {} with headers {}", request.getMethod(), request.getURI(), request.getAllHeaders());
        HttpResponse response = client.execute(request);
        StatusLine line = response.getStatusLine();
        log.info("Received {}: {} with headers {}", line.getStatusCode(), line.getReasonPhrase(), response.getAllHeaders());
        String data = EntityUtils.toString(response.getEntity());
        log.info("Received response as string {}", data);
        return data;
    } catch (IOException ioe) {
        log.error("Could not execute request", ioe);
        query.setFailure("Could not execute request");
        query.addMessage(ioe.toString());
    } catch (NullPointerException npe) {
        log.error("Received no response", npe);
        query.setFailure("Received no response");
        query.addMessage(npe.toString());
    }
    return null;
}
 
源代码19 项目: simple_net_framework   文件: HttpUrlConnStack.java
private Response fetchResponse(HttpURLConnection connection) throws IOException {

        // Initialize HttpResponse with data from the HttpURLConnection.
        ProtocolVersion protocolVersion = new ProtocolVersion("HTTP", 1, 1);
        int responseCode = connection.getResponseCode();
        if (responseCode == -1) {
            throw new IOException("Could not retrieve response code from HttpUrlConnection.");
        }
        // 状态行数据
        StatusLine responseStatus = new BasicStatusLine(protocolVersion,
                connection.getResponseCode(), connection.getResponseMessage());
        // 构建response
        Response response = new Response(responseStatus);
        // 设置response数据
        response.setEntity(entityFromURLConnwction(connection));
        addHeadersToResponse(response, connection);
        return response;
    }
 
源代码20 项目: JavaTutorial   文件: HttpClientBasic.java
private void processResponse(CloseableHttpResponse response) 
            throws UnsupportedOperationException, IOException {
        try {
            // 获取响应头
            Header[] headers = response.getAllHeaders();
            for (Header header : headers) {
                _logger.info(header.getName() + ":" + header.getValue());
            }
            
            // 获取状态信息
            StatusLine sl =response.getStatusLine();
            _logger.info( String.format("ProtocolVersion:%s, StatusCode:%d, Desc:%s", 
                    sl.getProtocolVersion().toString(), sl.getStatusCode(), sl.getReasonPhrase()) );
            
            // 获取响应内容
            HttpEntity entity = response.getEntity();
            _logger.info( String.format("ContentType:%s, Length:%d, Encoding:%s", 
                    null == entity.getContentType() ? "" : entity.getContentType().getValue(), 
                    entity.getContentLength(),
                    null == entity.getContentEncoding() ? "" : entity.getContentEncoding().getValue()) );
            _logger.info(EntityUtils.toString(entity, _charset));
//            _logger.info( IOUtils.toString(entity.getContent(), _charset) ); // 大部分情况下效果与上行语句等同,但实现上的编码处理不同
        } finally {
            response.close();
        }
    }
 
源代码21 项目: nexus-public   文件: ProxyFacetSupport.java
private <X extends Throwable> void logContentOrThrow(@Nullable final Content content,
                                                     final Context context,
                                                     @Nullable final StatusLine statusLine,
                                                     final X exception) throws X
{
  String logMessage = buildLogContentMessage(content, statusLine);
  String repositoryName = context.getRepository().getName();
  String contextUrl = getUrl(context);

  if (content != null) {
    log.debug(logMessage, exception, repositoryName, contextUrl, statusLine);
  }
  else {
    if (exception instanceof RemoteBlockedIOException) {
      // trace because the blocked status of a repo is typically discoverable in the UI and other log messages
      log.trace(logMessage, exception, repositoryName, contextUrl, statusLine, exception);
    }
    else if (log.isDebugEnabled()) {
      log.warn(logMessage, exception, repositoryName, contextUrl, statusLine, exception);
    }
    else {
      log.warn(logMessage, exception, repositoryName, contextUrl, statusLine);
    }
    throw exception;
  }
}
 
源代码22 项目: sdb-mall   文件: HttpRequest.java
public synchronized static String postData(String url) throws Exception {
       CloseableHttpClient httpclient = HttpClients.createDefault();
       HttpPost httpPost = new HttpPost(url);
       CloseableHttpResponse response = httpclient.execute(httpPost);
       String result = "";
       try {
           StatusLine statusLine = response.getStatusLine();
           HttpEntity entity = response.getEntity();
           // do something useful with the response body
           if (entity != null) {
               result = EntityUtils.toString(entity, "UTF-8");
           }else{
               LogKit.error("httpRequest postData2 error entity = null code = "+statusLine.getStatusCode());
           }
           // and ensure it is fully consumed
           //消耗掉response
           EntityUtils.consume(entity);
       } finally {
           response.close();
       }

       return result;
}
 
源代码23 项目: jkes   文件: HttpClient.java
public Response performRequest(String method, String host, String endpoint, Map<String, String> params, JSONObject entity) throws IOException {
    HttpRequestBase httpRequestBase = buildRequest(method, host, endpoint, params, entity);

    try (CloseableHttpResponse response = httpclient.execute(httpRequestBase)) {
        StatusLine statusLine = response.getStatusLine();
        HttpEntity responseEntity = response.getEntity();

        Response resp = Response.builder()
                .statusCode(statusLine.getStatusCode())
                .content(responseEntity == null ? null : EntityUtils.toString(responseEntity))
                .build();

        EntityUtils.consume(responseEntity);

        return resp;
    }
}
 
private static CloseableHttpClient recordHttpClientForMultipleResponsesWithContentAndStatusCode(List<String> contentPayloads, List<Integer> statusCodes) throws IOException {
    CloseableHttpResponse httpResponseMock = mock(CloseableHttpResponse.class);

    List<HttpEntity> httpEntities = contentPayloads.stream().map(ConfluenceRestClientTest::recordHttpEntityForContent).collect(toList());
    when(httpResponseMock.getEntity())
            .thenReturn(httpEntities.get(0), httpEntities.subList(1, httpEntities.size()).toArray(new HttpEntity[httpEntities.size() - 1]));

    List<StatusLine> statusLines = statusCodes.stream().map((statusCode) -> recordStatusLine(statusCode, null)).collect(toList());
    when(httpResponseMock.getStatusLine())
            .thenReturn(statusLines.get(0), statusLines.subList(1, statusLines.size()).toArray(new StatusLine[statusLines.size() - 1]));

    CloseableHttpClient httpClientMock = anyCloseableHttpClient();
    when(httpClientMock.execute(any(HttpRequestBase.class))).thenReturn(httpResponseMock);

    return httpClientMock;
}
 
源代码25 项目: timbuctoo   文件: ElasticSearchFilter.java
@Override
public Tuple<Boolean, String> isHealthy() {
  try {
    final Response response = restClient.performRequest(METHOD_GET, "_cluster/health");
    final StatusLine statusLine = response.getStatusLine();
    if (statusLine.getStatusCode() != 200) {
      return Tuple.tuple(false, "Request failed: " + statusLine.getReasonPhrase());
    }

    final JsonNode jsonNode = OBJECT_MAPPER.readTree(response.getEntity().getContent());
    final String status = jsonNode.get("status").asText();
    if (status.equals("red")) {
      return Tuple.tuple(false, "Elasticsearch cluster status is 'red'.");
    }

    return Tuple.tuple(true, "Elasticsearch filter is healthy.");
  } catch (IOException e) {
    LOG.error("Elasticsearch request failed", e);
    return Tuple.tuple(false, "Request threw an exception: " + e.getMessage());
  }
}
 
源代码26 项目: nextcloud-java-api   文件: ConnectorCommon.java
private R handleResponse(ResponseParser<R> parser, HttpResponse response) throws IOException
{
    StatusLine statusLine= response.getStatusLine();
    if (statusLine.getStatusCode() == HttpStatus.SC_OK)
    {
        HttpEntity entity = response.getEntity();
        if (entity != null)
        {
            Charset charset = ContentType.getOrDefault(entity).getCharset();
            Reader reader = new InputStreamReader(entity.getContent(), charset);
            return parser.parseResponse(reader);
        }
        throw new NextcloudApiException("Empty response received");
    }
    throw new NextcloudApiException(String.format("Request failed with %d %s", statusLine.getStatusCode(), statusLine.getReasonPhrase()));
}
 
源代码27 项目: android-discourse   文件: RestTask.java
@Override
protected RestResult doInBackground(String... args) {
    try {
        request = createRequest();
        if (isCancelled())
            throw new InterruptedException();
        OAuthConsumer consumer = Session.getInstance().getOAuthConsumer();
        if (consumer != null) {
            AccessToken accessToken = Session.getInstance().getAccessToken();
            if (accessToken != null) {
                consumer.setTokenWithSecret(accessToken.getKey(), accessToken.getSecret());
            }
            consumer.sign(request);
        }
        request.setHeader("Accept-Language", Locale.getDefault().getLanguage());
        request.setHeader("API-Client", String.format("uservoice-android-%s", UserVoice.getVersion()));
        AndroidHttpClient client = AndroidHttpClient.newInstance(String.format("uservoice-android-%s", UserVoice.getVersion()), Session.getInstance().getContext());
        if (isCancelled())
            throw new InterruptedException();
        // TODO it would be nice to find a way to abort the request on cancellation
        HttpResponse response = client.execute(request);
        if (isCancelled())
            throw new InterruptedException();
        HttpEntity responseEntity = response.getEntity();
        StatusLine responseStatus = response.getStatusLine();
        int statusCode = responseStatus != null ? responseStatus.getStatusCode() : 0;
        String body = responseEntity != null ? EntityUtils.toString(responseEntity) : null;
        client.close();
        if (isCancelled())
            throw new InterruptedException();
        return new RestResult(statusCode, new JSONObject(body));
    } catch (Exception e) {
        return new RestResult(e);
    }
}
 
源代码28 项目: android-discourse   文件: MockHttpClient.java
@Override
public HttpResponse execute(HttpUriRequest request, HttpContext context) {
    requestExecuted = request;
    StatusLine statusLine = new BasicStatusLine(new ProtocolVersion("HTTP", 1, 1), mStatusCode, "");
    HttpResponse response = new BasicHttpResponse(statusLine);
    response.setEntity(mResponseEntity);

    return response;
}
 
源代码29 项目: device-database   文件: BasicNetwork.java
/**
 * Logs requests that took over SLOW_REQUEST_THRESHOLD_MS to complete.
 */
private void logSlowRequests(long requestLifetime, Request<?> request,
        byte[] responseContents, StatusLine statusLine) {
    if (DEBUG || requestLifetime > SLOW_REQUEST_THRESHOLD_MS) {
        VolleyLog.d("HTTP response for request=<%s> [lifetime=%d], [size=%s], " +
                "[rc=%d], [retryCount=%s]", request, requestLifetime,
                responseContents != null ? responseContents.length : "null",
                statusLine.getStatusCode(), request.getRetryPolicy().getCurrentRetryCount());
    }
}
 
/**
 * unmarshallIngestResponse
 * Given an HttpResponse object - attempts to deserialize it into
 * an IngestResponse object
 *
 * @param response the HTTPResponse we want to distill into an IngestResponse
 * @return An IngestResponse with all of the parsed out information
 * @throws IOException      - if our entity is somehow corrupt or we can't get it
 * @throws BackOffException if we have a 503 response
 */
public static IngestResponse unmarshallIngestResponse(HttpResponse response)
    throws IOException, IngestResponseException
{
  //we can't unmarshall a null response
  if (response == null)
  {
    LOGGER.warn("Null argument passed to unmarshallIngestResponse");
    throw new IllegalArgumentException();
  }

  //Grab the status line from the response
  StatusLine statusLine = response.getStatusLine();

  //If we didn't get a good status code, handle it
  if (!isStatusOK(statusLine))
  {

    //Exception status
    LOGGER.warn("Exceptional Status Code found in unmarshallInsert Response  - {}",
        statusLine.getStatusCode());

    handleExceptionalStatus(statusLine, response);
    return null;
  }

  //grab the response entity
  String blob = EntityUtils.toString(response.getEntity());

  //Read out the blob entity into a class
  return mapper.readValue(blob, IngestResponse.class);
}
 
 类所在包
 同包方法