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

项目:boohee_v5.6    文件:RangeFileAsyncHttpResponseHandler.java   
public void sendResponseMessage(HttpResponse response) throws IOException {
    if (!Thread.currentThread().isInterrupted()) {
        StatusLine status = response.getStatusLine();
        if (status.getStatusCode() == 416) {
            if (!Thread.currentThread().isInterrupted()) {
                sendSuccessMessage(status.getStatusCode(), response.getAllHeaders(), null);
            }
        } else if (status.getStatusCode() >= 300) {
            if (!Thread.currentThread().isInterrupted()) {
                sendFailureMessage(status.getStatusCode(), response.getAllHeaders(), null,
                        new HttpResponseException(status.getStatusCode(), status
                                .getReasonPhrase()));
            }
        } else if (!Thread.currentThread().isInterrupted()) {
            Header header = response.getFirstHeader(AsyncHttpClient.HEADER_CONTENT_RANGE);
            if (header == null) {
                this.append = false;
                this.current = 0;
            } else {
                Log.v(LOG_TAG, "Content-Range: " + header.getValue());
            }
            sendSuccessMessage(status.getStatusCode(), response.getAllHeaders(),
                    getResponseData(response.getEntity()));
        }
    }
}
项目:sealtalk-android-master    文件:AsyncHttpResponseHandler.java   
@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);
            }
        }
    }
}
项目:q-mail    文件:WebDavFolderTest.java   
@Test
public void folder_can_handle_empty_response_to_body_request() throws MessagingException, IOException {
    setupStoreForMessageFetching();
    List<WebDavMessage> messages = setup25MessagesToFetch();

    when(mockHttpClient.executeOverride(any(HttpUriRequest.class), any(HttpContext.class))).thenAnswer(
            new Answer<HttpResponse>() {
                @Override
                public HttpResponse answer(InvocationOnMock invocation) throws Throwable {
                    HttpResponse httpResponse = mock(HttpResponse.class);
                    StatusLine statusLine = mock(StatusLine.class);
                    when(httpResponse.getStatusLine()).thenReturn(statusLine);
                    when(statusLine.getStatusCode()).thenReturn(200);
                    return httpResponse;
                }
            });

    FetchProfile profile = new FetchProfile();
    profile.add(FetchProfile.Item.BODY_SANE);
    folder.fetch(messages, profile, listener);
    verify(listener, times(25)).messageStarted(any(String.class), anyInt(), eq(25));
    verify(listener, times(25)).messageFinished(any(WebDavMessage.class), anyInt(), eq(25));
}
项目:rongyunDemo    文件:BinaryHttpResponseHandler.java   
@Override
public final void sendResponseMessage(HttpResponse response) throws IOException {
    StatusLine status = response.getStatusLine();
    Header[] contentTypeHeaders = response.getHeaders("Content-Type");
    if (contentTypeHeaders.length != 1) {
        //malformed/ambiguous HTTP Header, ABORT!
        sendFailureMessage(status.getStatusCode(), response.getAllHeaders(), null, new HttpResponseException(status.getStatusCode(), "None, or more than one, Content-Type Header found!"));
        return;
    }
    Header contentTypeHeader = contentTypeHeaders[0];
    boolean foundAllowedContentType = false;
    for (String anAllowedContentType : getAllowedContentTypes()) {
        try {
            if (Pattern.matches(anAllowedContentType, contentTypeHeader.getValue())) {
                foundAllowedContentType = true;
            }
        } catch (PatternSyntaxException e) {
        }
    }
    if (!foundAllowedContentType) {
        //Content-Type not in allowed list, ABORT!
        sendFailureMessage(status.getStatusCode(), response.getAllHeaders(), null, new HttpResponseException(status.getStatusCode(), "Content-Type not allowed!"));
        return;
    }
    super.sendResponseMessage(response);
}
项目:Mobike    文件:AsyncHttpResponseHandler.java   
@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);
            }
        }
    }
}
项目:rongyunDemo    文件:AsyncHttpResponseHandler.java   
@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);
            }
        }
    }
}
项目:educational-plugin    文件:EduStepicConnector.java   
private static void postSubmission(boolean passed, StepicWrappers.AttemptWrapper.Attempt attempt,
                                   ArrayList<StepicWrappers.SolutionFile> files) throws IOException {
  final HttpPost request = new HttpPost(EduStepicNames.STEPIC_API_URL + EduStepicNames.SUBMISSIONS);

  String requestBody = new Gson().toJson(new StepicWrappers.SubmissionWrapper(attempt.id, passed ? "1" : "0", files));
  request.setEntity(new StringEntity(requestBody, ContentType.APPLICATION_JSON));
  final CloseableHttpClient client = EduStepicAuthorizedClient.getHttpClient();
  if (client == null) return;
  final CloseableHttpResponse response = client.execute(request);
  final HttpEntity responseEntity = response.getEntity();
  final String responseString = responseEntity != null ? EntityUtils.toString(responseEntity) : "";
  final StatusLine line = response.getStatusLine();
  EntityUtils.consume(responseEntity);
  if (line.getStatusCode() != HttpStatus.SC_CREATED) {
    LOG.error("Failed to make submission " + responseString);
  }
}
项目:uavstack    文件:AsyncReqProcWithHttpClientCallback.java   
protected int getStatusCode() {

        StatusLine sl = null;
        try {
            sl = response.getStatusLine();
        }
        catch (Exception e) {
            // ignore
        }

        if (null == sl) {
            // as BAT REQUEST
            return 400;
        }

        return sl.getStatusCode();
    }
项目:elasticsearch_my    文件:HeapBufferedAsyncResponseConsumerTests.java   
public void testResponseProcessing() throws Exception {
    ContentDecoder contentDecoder = mock(ContentDecoder.class);
    IOControl ioControl = mock(IOControl.class);
    HttpContext httpContext = mock(HttpContext.class);

    HeapBufferedAsyncResponseConsumer consumer = spy(new HeapBufferedAsyncResponseConsumer(TEST_BUFFER_LIMIT));

    ProtocolVersion protocolVersion = new ProtocolVersion("HTTP", 1, 1);
    StatusLine statusLine = new BasicStatusLine(protocolVersion, 200, "OK");
    HttpResponse httpResponse = new BasicHttpResponse(statusLine);
    httpResponse.setEntity(new StringEntity("test", ContentType.TEXT_PLAIN));

    //everything goes well
    consumer.responseReceived(httpResponse);
    consumer.consumeContent(contentDecoder, ioControl);
    consumer.responseCompleted(httpContext);

    verify(consumer).releaseResources();
    verify(consumer).buildResult(httpContext);
    assertTrue(consumer.isDone());
    assertSame(httpResponse, consumer.getResult());

    consumer.responseCompleted(httpContext);
    verify(consumer, times(1)).releaseResources();
    verify(consumer, times(1)).buildResult(httpContext);
}
项目:nifi-atlas    文件:NiFiApiClient.java   
private String getEntity(URI url) throws IOException {
    final HttpGet get = new HttpGet(url);
    get.setConfig(requestConfig);
    get.setHeader("Accept", "application/json");

    HttpClientBuilder clientBuilder = HttpClients.custom();
    if (sslContext != null) {
        clientBuilder.setSslcontext(sslContext);
    }

    try (CloseableHttpClient httpClient = clientBuilder.build()) {

        try (CloseableHttpResponse response = httpClient.execute(get)) {

            final StatusLine statusLine = response.getStatusLine();
            final int statusCode = statusLine.getStatusCode();
            if (200 != statusCode) {
                final String msg = String.format("Failed to get entity from %s, response=%d:%s",
                        get.getURI(), statusCode, statusLine.getReasonPhrase());
                throw new RuntimeException(msg);
            }
            final HttpEntity entity = response.getEntity();
            return EntityUtils.toString(entity);
        }
    }
}
项目:elasticsearch_my    文件:RestClientMultipleHostsTests.java   
@Before
@SuppressWarnings("unchecked")
public void createRestClient() throws IOException {
    CloseableHttpAsyncClient httpClient = mock(CloseableHttpAsyncClient.class);
    when(httpClient.<HttpResponse>execute(any(HttpAsyncRequestProducer.class), any(HttpAsyncResponseConsumer.class),
           any(HttpClientContext.class), any(FutureCallback.class))).thenAnswer(new Answer<Future<HttpResponse>>() {
        @Override
        public Future<HttpResponse> answer(InvocationOnMock invocationOnMock) throws Throwable {
            HttpAsyncRequestProducer requestProducer = (HttpAsyncRequestProducer) invocationOnMock.getArguments()[0];
            HttpUriRequest request = (HttpUriRequest)requestProducer.generateRequest();
            HttpHost httpHost = requestProducer.getTarget();
            HttpClientContext context = (HttpClientContext) invocationOnMock.getArguments()[2];
            assertThat(context.getAuthCache().get(httpHost), instanceOf(BasicScheme.class));
            FutureCallback<HttpResponse> futureCallback = (FutureCallback<HttpResponse>) invocationOnMock.getArguments()[3];
            //return the desired status code or exception depending on the path
            if (request.getURI().getPath().equals("/soe")) {
                futureCallback.failed(new SocketTimeoutException(httpHost.toString()));
            } else if (request.getURI().getPath().equals("/coe")) {
                futureCallback.failed(new ConnectTimeoutException(httpHost.toString()));
            } else if (request.getURI().getPath().equals("/ioe")) {
                futureCallback.failed(new IOException(httpHost.toString()));
            } else {
                int statusCode = Integer.parseInt(request.getURI().getPath().substring(1));
                StatusLine statusLine = new BasicStatusLine(new ProtocolVersion("http", 1, 1), statusCode, "");
                futureCallback.completed(new BasicHttpResponse(statusLine));
            }
            return null;
        }
    });
    int numHosts = RandomNumbers.randomIntBetween(getRandom(), 2, 5);
    httpHosts = new HttpHost[numHosts];
    for (int i = 0; i < numHosts; i++) {
        httpHosts[i] = new HttpHost("localhost", 9200 + i);
    }
    failureListener = new HostsTrackingFailureListener();
    restClient = new RestClient(httpClient, 10000, new Header[0], httpHosts, null, failureListener);
}
项目: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()));
}
项目:lams    文件:BasicLineParser.java   
public final static
    StatusLine parseStatusLine(final String value,
                               LineParser parser)
    throws ParseException {

    if (value == null) {
        throw new IllegalArgumentException
            ("Value to parse may not be null.");
    }

    if (parser == null)
        parser = BasicLineParser.DEFAULT;

    CharArrayBuffer buffer = new CharArrayBuffer(value.length());
    buffer.append(value);
    ParserCursor cursor = new ParserCursor(0, value.length());
    return parser.parseStatusLine(buffer, cursor);
}
项目:lams    文件:BasicLineFormatter.java   
/**
 * Actually formats a status line.
 * Called from {@link #formatStatusLine}.
 *
 * @param buffer    the empty buffer into which to format,
 *                  never <code>null</code>
 * @param statline  the status line to format, never <code>null</code>
 */
protected void doFormatStatusLine(final CharArrayBuffer buffer,
                                  final StatusLine statline) {

    int len = estimateProtocolVersionLen(statline.getProtocolVersion())
        + 1 + 3 + 1; // room for "HTTP/1.1 200 "
    final String reason = statline.getReasonPhrase();
    if (reason != null) {
        len += reason.length();
    }
    buffer.ensureCapacity(len);

    appendProtocolVersion(buffer, statline.getProtocolVersion());
    buffer.append(' ');
    buffer.append(Integer.toString(statline.getStatusCode()));
    buffer.append(' '); // keep whitespace even if reason phrase is empty
    if (reason != null) {
        buffer.append(reason);
    }
}
项目:educational-plugin    文件:CCStepicConnector.java   
public static void deleteTask(@NotNull final Integer task, Project project) {
  final HttpDelete request = new HttpDelete(EduStepicNames.STEPIC_API_URL + EduStepicNames.STEP_SOURCES + task);
  ApplicationManager.getApplication().invokeLater(() -> {
    try {
      final CloseableHttpClient client = EduStepicAuthorizedClient.getHttpClient();
      if (client == null) return;
      final CloseableHttpResponse response = client.execute(request);
      final HttpEntity responseEntity = response.getEntity();
      final String responseString = responseEntity != null ? EntityUtils.toString(responseEntity) : "";
      EntityUtils.consume(responseEntity);
      final StatusLine line = response.getStatusLine();
      if (line.getStatusCode() != HttpStatus.SC_NO_CONTENT) {
        LOG.error("Failed to delete task " + responseString);
        showErrorNotification(project, "Failed to delete task ", responseString);
      }
    }
    catch (IOException e) {
      LOG.error(e.getMessage());
    }
  });
}
项目:android-project-gallery    文件:AsyncHttpResponseHandler.java   
@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);
            }
        }
    }
}
项目:WeChatLuckyMoney    文件:UpdateTask.java   
@Override
protected String doInBackground(String... uri) {
    HttpClient httpclient = new DefaultHttpClient();
    HttpResponse response;
    String responseString = null;
    try {
        response = httpclient.execute(new HttpGet(uri[0]));
        StatusLine statusLine = response.getStatusLine();
        if (statusLine.getStatusCode() == 200) {
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            response.getEntity().writeTo(out);
            responseString = out.toString();
            out.close();
        } else {
            // Close the connection.
            response.getEntity().getContent().close();
            throw new IOException(statusLine.getReasonPhrase());
        }
    } catch (Exception e) {
        return null;
    }
    return responseString;
}
项目:cyberduck    文件:SwiftExceptionMappingServiceTest.java   
@Test
public void testMap() throws Exception {
    assertEquals("Message. 500 reason. Please contact your web hosting service provider for assistance.", new SwiftExceptionMappingService().map(
            new GenericException("message", null, new StatusLine() {
                @Override
                public ProtocolVersion getProtocolVersion() {
                    throw new UnsupportedOperationException();
                }

                @Override
                public int getStatusCode() {
                    return 500;
                }

                @Override
                public String getReasonPhrase() {
                    return "reason";
                }
            })).getDetail());
}
项目:XXXX    文件:ApacheHttpClient.java   
Response toFeignResponse(HttpResponse httpResponse) throws IOException {
  StatusLine statusLine = httpResponse.getStatusLine();
  int statusCode = statusLine.getStatusCode();

  String reason = statusLine.getReasonPhrase();

  Map<String, Collection<String>> headers = new HashMap<String, Collection<String>>();
  for (Header header : httpResponse.getAllHeaders()) {
    String name = header.getName();
    String value = header.getValue();

    Collection<String> headerValues = headers.get(name);
    if (headerValues == null) {
      headerValues = new ArrayList<String>();
      headers.put(name, headerValues);
    }
    headerValues.add(value);
  }

  return Response.builder()
          .status(statusCode)
          .reason(reason)
          .headers(headers)
          .body(toFeignBody(httpResponse))
          .build();
}
项目:stock-api-sdk    文件:HttpUtilsTest.java   
@Test(groups = "HttpUtils.doGet")
public void doGet_should_return_null_since_httpClient_execute_returned_with_unknown_response_code()
        throws ClientProtocolException, IOException {

    String succResponse = "Test Response";

    CloseableHttpResponse httpResponse = PowerMockito
            .mock(CloseableHttpResponse.class);
    StatusLine statusLine = PowerMockito.mock(StatusLine.class);

    StringEntity entity = new StringEntity(succResponse);

    PowerMockito.spy(HttpUtils.class);

    try {
        PowerMockito.doReturn(mockHttpClient).when(HttpUtils.class,
                "initialize");
    } catch (Exception e1) {
        Assert.fail("Couldn't mock the HttpUtils.initialize method!", e1);
    }

    // and:
    PowerMockito.when(statusLine.getStatusCode()).thenReturn(600);
    PowerMockito.when(httpResponse.getEntity()).thenReturn(entity);
    PowerMockito.when(httpResponse.getStatusLine()).thenReturn(statusLine);

    PowerMockito.when(mockHttpClient.execute(Mockito.any(HttpGet.class)))
            .thenReturn(httpResponse);
    HashMap<String, String> headers = new HashMap<String, String>();

    headers.put("test", "value");

    try {
        String response = HttpUtils.doGet("http://example.com", headers);

        Assert.assertNull(response);
    } catch (StockException e) {
        Assert.fail("Exception occured while calling HttpUtils.doGet!", e);
    }
}
项目:stock-api-sdk    文件:HttpUtilsTest.java   
@Test(groups = "HttpUtils.doGet")
public void doGet_should_return_string_response_since_httpClient_execute_returned_with_success()
        throws ClientProtocolException, IOException {

    String succResponse = "Test Response";

    CloseableHttpResponse httpResponse = PowerMockito
            .mock(CloseableHttpResponse.class);
    StatusLine statusLine = PowerMockito.mock(StatusLine.class);

    StringEntity entity = new StringEntity(succResponse);

    PowerMockito.spy(HttpUtils.class);

    try {
        PowerMockito.doReturn(mockHttpClient).when(HttpUtils.class,
                "initialize");
    } catch (Exception e1) {
        Assert.fail("Couldn't mock the HttpUtils.initialize method!", e1);
    }

    // and:
    PowerMockito.when(statusLine.getStatusCode()).thenReturn(200);
    PowerMockito.when(httpResponse.getEntity()).thenReturn(entity);
    PowerMockito.when(httpResponse.getStatusLine()).thenReturn(statusLine);

    PowerMockito.when(mockHttpClient.execute(Mockito.any(HttpGet.class)))
            .thenReturn(httpResponse);
    HashMap<String, String> headers = new HashMap<String, String>();

    headers.put("test", "value");

    try {
        String response = HttpUtils.doGet("http://example.com", headers);

        Assert.assertEquals(response, succResponse);
    } catch (StockException e) {
        Assert.fail("Exception occured while calling HttpUtils.doGet!", e);
    }
}
项目:stock-api-sdk    文件:HttpUtilsTest.java   
@Test(groups = "HttpUtils.doGet", expectedExceptions = StockException.class)
public void doGet_should_throw_stockexception_since_entityutils_tostring_throws_exception()
        throws ClientProtocolException, IOException, StockException {

    CloseableHttpResponse httpResponse = PowerMockito
            .mock(CloseableHttpResponse.class);
    StatusLine statusLine = PowerMockito.mock(StatusLine.class);

    PowerMockito.spy(HttpUtils.class);

    try {
        PowerMockito.doReturn(mockHttpClient).when(HttpUtils.class,
                "initialize");
    } catch (Exception e1) {
        Assert.fail("Couldn't mock the HttpUtils.initialize method!", e1);
    }

    // and:
    PowerMockito.when(statusLine.getStatusCode()).thenReturn(400);
    PowerMockito.when(httpResponse.getEntity()).thenReturn(null);
    PowerMockito.when(httpResponse.getStatusLine()).thenReturn(statusLine);

    PowerMockito.when(mockHttpClient.execute(Mockito.any(HttpGet.class)))
            .thenReturn(httpResponse);

    HttpUtils.doGet("http://example.com", null);
}
项目:stock-api-sdk    文件:HttpUtilsTest.java   
@Test(groups = "HttpUtils.doPost")
public void doPost_should_throw_stockexception_since_httpClient_execute_returned_with_bad_request()
        throws ClientProtocolException, IOException {

    String errorResponse = "{ \"error\": { \"message\": \"Test Response\" } }";

    CloseableHttpResponse httpResponse = PowerMockito
            .mock(CloseableHttpResponse.class);
    StatusLine statusLine = PowerMockito.mock(StatusLine.class);

    StringEntity entity = new StringEntity(errorResponse);

    PowerMockito.spy(HttpUtils.class);

    try {
        PowerMockito.doReturn(mockHttpClient).when(HttpUtils.class,
                "initialize");
    } catch (Exception e1) {
        Assert.fail("Couldn't mock the HttpUtils.initialize method!", e1);
    }

    // and:
    PowerMockito.when(statusLine.getStatusCode()).thenReturn(400);
    PowerMockito.when(httpResponse.getEntity()).thenReturn(entity);
    PowerMockito.when(httpResponse.getStatusLine()).thenReturn(statusLine);

    PowerMockito.when(mockHttpClient.execute(Mockito.any(HttpGet.class)))
            .thenReturn(httpResponse);

    try {
        HttpUtils.doPost("http://example.com", null,
                errorResponse.getBytes(), ContentType.TEXT_PLAIN);

        Assert.fail("Expected the StockException since the httpclient.execute returned with bad request!");
    } catch (StockException e) {
        Assert.assertEquals(e.getMessage(), errorResponse);
        Assert.assertEquals(e.getCode(), 400);
    }
}
项目:stock-api-sdk    文件:HttpUtilsTest.java   
@Test(groups = "HttpUtils.doPost")
public void doPost_should_throw_stockexception_since_httpClient_execute_returned_with_internal_server_error()
        throws ClientProtocolException, IOException {

    CloseableHttpResponse httpResponse = PowerMockito
            .mock(CloseableHttpResponse.class);
    StatusLine statusLine = PowerMockito.mock(StatusLine.class);

    PowerMockito.spy(HttpUtils.class);

    try {
        PowerMockito.doReturn(mockHttpClient).when(HttpUtils.class,
                "initialize");
    } catch (Exception e1) {
        Assert.fail("Couldn't mock the HttpUtils.initialize method!", e1);
    }

    // and:
    PowerMockito.when(statusLine.getStatusCode()).thenReturn(500);
    PowerMockito.when(httpResponse.getStatusLine()).thenReturn(statusLine);

    PowerMockito.when(mockHttpClient.execute(Mockito.any(HttpGet.class)))
            .thenReturn(httpResponse);

    try {
        HttpUtils.doPost("http://example.com", null, null,
                ContentType.TEXT_PLAIN);

        Assert.fail("Expected the StockException since the httpclient.execute returned with bad request!");
    } catch (StockException e) {
        Assert.assertEquals(e.getMessage(),
                "API returned with Server Error");
        Assert.assertEquals(e.getCode(), 500);
    }
}
项目:plugin-bt-jira    文件:JiraSudoHttpResponseCallbackTest.java   
@Test
public void acceptResponse200() {
    final CloseableHttpResponse response = Mockito.mock(CloseableHttpResponse.class);
    final StatusLine statusLine = Mockito.mock(StatusLine.class);
    Mockito.when(response.getStatusLine()).thenReturn(statusLine);
    Mockito.when(statusLine.getStatusCode()).thenReturn(200);
    Assert.assertFalse(jiraSudoHttpResponseCallback.acceptResponse(response));
}
项目:stock-api-sdk    文件:HttpUtilsTest.java   
@Test(groups = "HttpUtils.doMultiPart")
public void doMultiPart_should_throw_stockexception_since_httpClient_execute_returned_with_bad_request()
        throws ClientProtocolException, IOException {

    String errorResponse = "{ \"error\": { \"message\": \"Test Response\" } }";

    CloseableHttpResponse httpResponse = PowerMockito
            .mock(CloseableHttpResponse.class);
    StatusLine statusLine = PowerMockito.mock(StatusLine.class);

    StringEntity entity = new StringEntity(errorResponse);

    PowerMockito.spy(HttpUtils.class);

    try {
        PowerMockito.doReturn(mockHttpClient).when(HttpUtils.class,
                "initialize");
    } catch (Exception e1) {
        Assert.fail("Couldn't mock the HttpUtils.initialize method!", e1);
    }

    // and:
    PowerMockito.when(statusLine.getStatusCode()).thenReturn(400);
    PowerMockito.when(httpResponse.getEntity()).thenReturn(entity);
    PowerMockito.when(httpResponse.getStatusLine()).thenReturn(statusLine);

    PowerMockito.when(mockHttpClient.execute(Mockito.any(HttpGet.class)))
            .thenReturn(httpResponse);

    try {
        HttpUtils.doMultiPart("http://example.com",
                errorResponse.getBytes(), null);

        Assert.fail("Expected the StockException since the httpclient.execute returned with bad request!");
    } catch (StockException e) {
        Assert.assertEquals(e.getMessage(), errorResponse);
        Assert.assertEquals(e.getCode(), 400);
    }
}
项目:Reer    文件:HttpBuildCache.java   
@Override
public boolean load(BuildCacheKey key, BuildCacheEntryReader reader) throws BuildCacheException {
    final URI uri = root.resolve("./" + key.getHashCode());
    HttpGet httpGet = new HttpGet(uri);
    CloseableHttpResponse response = null;
    try {
        response = httpClient.execute(httpGet);
        StatusLine statusLine = response.getStatusLine();
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("Response for GET {}: {}", safeUri(uri), statusLine);
        }
        int statusCode = statusLine.getStatusCode();
        if (statusCode >= 200 && statusCode < 300) {
            reader.readFrom(response.getEntity().getContent());
            return true;
        } else if (statusCode == 404) {
            return false;
        } else {
            // TODO: We should consider different status codes as fatal/recoverable
            throw new BuildCacheException(String.format("For key '%s', using %s response status %d: %s", key, getDescription(), statusCode, statusLine.getReasonPhrase()));
        }
    } catch (IOException e) {
        // TODO: We should consider different types of exceptions as fatal/recoverable.
        // Right now, everything is considered recoverable.
        throw new BuildCacheException(String.format("loading key '%s' from %s", key, getDescription()), e);
    } finally {
        HttpClientUtils.closeQuietly(response);
    }
}
项目:boohee_v5.6    文件:BasicNetwork.java   
private void logSlowRequests(long requestLifetime, Request<?> request, byte[] responseContents, StatusLine statusLine) {
    if (DEBUG || requestLifetime > ((long) SLOW_REQUEST_THRESHOLD_MS)) {
        String str = "HTTP response for request=<%s> [lifetime=%d], [size=%s], [rc=%d], [retryCount=%s]";
        Object[] objArr = new Object[5];
        objArr[0] = request;
        objArr[1] = Long.valueOf(requestLifetime);
        objArr[2] = responseContents != null ? Integer.valueOf(responseContents.length) : "null";
        objArr[3] = Integer.valueOf(statusLine.getStatusCode());
        objArr[4] = Integer.valueOf(request.getRetryPolicy().getCurrentRetryCount());
        VolleyLog.d(str, objArr);
    }
}
项目:educational-plugin    文件:CCStepicConnector.java   
public static int postLesson(@NotNull final Project project, @NotNull final Lesson lesson) {
  if (!checkIfAuthorized(project, "postLesson")) return -1;

  final HttpPost request = new HttpPost(EduStepicNames.STEPIC_API_URL + "/lessons");

  String requestBody = new Gson().toJson(new StepicWrappers.LessonWrapper(lesson));
  request.setEntity(new StringEntity(requestBody, ContentType.APPLICATION_JSON));

  try {
    final CloseableHttpClient client = EduStepicAuthorizedClient.getHttpClient();
    if (client == null) return -1;
    final CloseableHttpResponse response = client.execute(request);
    final HttpEntity responseEntity = response.getEntity();
    final String responseString = responseEntity != null ? EntityUtils.toString(responseEntity) : "";
    final StatusLine line = response.getStatusLine();
    EntityUtils.consume(responseEntity);
    if (line.getStatusCode() != HttpStatus.SC_CREATED) {
      final String message = FAILED_TITLE + "lesson ";
      LOG.error(message + responseString);
      showErrorNotification(project, message, responseString);
      return 0;
    }
    final Lesson postedLesson = new Gson().fromJson(responseString, RemoteCourse.class).getLessons(true).get(0);
    lesson.setId(postedLesson.getId());
    for (Task task : lesson.getTaskList()) {
      final ProgressIndicator indicator = ProgressManager.getInstance().getProgressIndicator();
      if (indicator != null) {
        indicator.checkCanceled();
      }
      postTask(project, task, postedLesson.getId());
    }
    return postedLesson.getId();
  }
  catch (IOException e) {
    LOG.error(e.getMessage());
  }
  return -1;
}
项目:GitHub    文件: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());
    }
}
项目:GitHub    文件: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;
}
项目:airgram    文件:HurlStack.java   
@Override
public HttpResponse performRequest(Request<?> request, Map<String, String> additionalHeaders)
        throws IOException, AuthFailureError {
    String url = request.getUrl();
    HashMap<String, String> map = new HashMap<String, String>();
    map.putAll(request.getHeaders());
    map.putAll(additionalHeaders);
    if (mUrlRewriter != null) {
        String rewritten = mUrlRewriter.rewriteUrl(url);
        if (rewritten == null) {
            throw new IOException("URL blocked by rewriter: " + url);
        }
        url = rewritten;
    }
    URL parsedUrl = new URL(url);
    HttpURLConnection connection = openConnection(parsedUrl, request);
    for (String headerName : map.keySet()) {
        connection.addRequestProperty(headerName, map.get(headerName));
    }
    setConnectionParametersForRequest(connection, request);
    // Initialize HttpResponse with data from the HttpURLConnection.
    ProtocolVersion protocolVersion = new ProtocolVersion("HTTP", 1, 1);
    int responseCode = connection.getResponseCode();
    if (responseCode == -1) {
        // -1 is returned by getResponseCode() if the response code could not be retrieved.
        // Signal to the caller that something was wrong with the connection.
        throw new IOException("Could not retrieve response code from HttpUrlConnection.");
    }
    StatusLine responseStatus = new BasicStatusLine(protocolVersion,
            connection.getResponseCode(), connection.getResponseMessage());
    BasicHttpResponse response = new BasicHttpResponse(responseStatus);
    if (hasResponseBody(request.getMethod(), responseStatus.getStatusCode())) {
        response.setEntity(entityFromConnection(connection));
    }
    for (Entry<String, List<String>> header : connection.getHeaderFields().entrySet()) {
        if (header.getKey() != null) {
            Header h = new BasicHeader(header.getKey(), header.getValue().get(0));
            response.addHeader(h);
        }
    }
    return response;
}
项目:elasticsearch_my    文件:SyncResponseListenerTests.java   
private static Response mockResponse() {
    ProtocolVersion protocolVersion = new ProtocolVersion("HTTP", 1, 1);
    RequestLine requestLine = new BasicRequestLine("GET", "/", protocolVersion);
    StatusLine statusLine = new BasicStatusLine(protocolVersion, 200, "OK");
    HttpResponse httpResponse = new BasicHttpResponse(statusLine);
    return new Response(requestLine, new HttpHost("localhost", 9200), httpResponse);
}
项目:elasticsearch_my    文件:FailureTrackingResponseListenerTests.java   
private static Response mockResponse() {
    ProtocolVersion protocolVersion = new ProtocolVersion("HTTP", 1, 1);
    RequestLine requestLine = new BasicRequestLine("GET", "/", protocolVersion);
    StatusLine statusLine = new BasicStatusLine(protocolVersion, 200, "OK");
    HttpResponse httpResponse = new BasicHttpResponse(statusLine);
    return new Response(requestLine, new HttpHost("localhost", 9200), httpResponse);
}
项目:Hotspot-master-devp    文件:SyncHttpHandler.java   
private ResponseStream handleResponse(HttpResponse response) throws HttpException, IOException {
    if (response == null) {
        throw new HttpException("response is null");
    }
    StatusLine status = response.getStatusLine();
    int statusCode = status.getStatusCode();
    if (statusCode < 300) {

        // Set charset from response header if it's exist.
        String responseCharset = OtherUtils.getCharsetFromHttpResponse(response);
        charset = TextUtils.isEmpty(responseCharset) ? charset : responseCharset;

        return new ResponseStream(response, charset, requestUrl, expiry);
    } else if (statusCode == 301 || statusCode == 302) {
        if (httpRedirectHandler == null) {
            httpRedirectHandler = new DefaultHttpRedirectHandler();
        }
        HttpRequestBase request = httpRedirectHandler.getDirectRequest(response);
        if (request != null) {
            return this.sendRequest(request);
        }
    } else if (statusCode == 416) {
        throw new HttpException(statusCode, "maybe the file has downloaded completely");
    } else {
        throw new HttpException(statusCode, status.getReasonPhrase());
    }
    return null;
}
项目:living-documentation    文件:ConfluenceRestClient.java   
private <T> T sendRequestAndFailIfNot20x(HttpRequestBase request, Function<HttpResponse, T> responseHandler) {
    return sendRequest(request, (response) -> {
        StatusLine statusLine = response.getStatusLine();
        if (statusLine.getStatusCode() < 200 || statusLine.getStatusCode() > 206) {
            throw new RequestFailedException(request, response);
        }

        return responseHandler.apply(response);
    });
}
项目:Codeforces    文件: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;
}
项目:letv    文件:AsyncHttpResponseHandler.java   
protected void sendResponseMessage(HttpResponse response) {
    Throwable e;
    StatusLine status = response.getStatusLine();
    String responseBody = null;
    try {
        HttpEntity temp = response.getEntity();
        if (temp != null) {
            HttpEntity entity = new BufferedHttpEntity(temp);
            try {
                responseBody = EntityUtils.toString(entity, "UTF-8");
            } catch (IOException e2) {
                e = e2;
                HttpEntity httpEntity = entity;
                sendFailureMessage(e, null);
                if (status.getStatusCode() >= 300) {
                    sendSuccessMessage(status.getStatusCode(), response.getAllHeaders(), responseBody);
                } else {
                    sendFailureMessage(new HttpResponseException(status.getStatusCode(), status.getReasonPhrase()), responseBody);
                }
            }
        }
    } catch (IOException e3) {
        e = e3;
        sendFailureMessage(e, null);
        if (status.getStatusCode() >= 300) {
            sendFailureMessage(new HttpResponseException(status.getStatusCode(), status.getReasonPhrase()), responseBody);
        } else {
            sendSuccessMessage(status.getStatusCode(), response.getAllHeaders(), responseBody);
        }
    }
    if (status.getStatusCode() >= 300) {
        sendFailureMessage(new HttpResponseException(status.getStatusCode(), status.getReasonPhrase()), responseBody);
    } else {
        sendSuccessMessage(status.getStatusCode(), response.getAllHeaders(), responseBody);
    }
}
项目:letv    文件:rcccrr.java   
private boolean b044C044C044Cьь044C(String str, String str2, String str3, String str4) throws ClientProtocolException, IOException {
    this.b041BЛЛ041BЛ041B = b044Cьь044Cь044C(str3);
    HttpPost httpPost = new HttpPost(bЛ041BЛЛЛ041B);
    String generateSignature = new crrcrc().generateSignature(str2, this.b041BЛЛ041BЛ041B, str4);
    httpPost.setEntity(new StringEntity(str4, "UTF-8"));
    httpPost.setHeaders(this.b041BЛЛ041BЛ041B);
    Object bььь044Cь044C = bььь044Cь044C(str, generateSignature, httpPost);
    HttpResponse execute = new DefaultHttpClient().execute(bььь044Cь044C);
    Log.d(b041BЛЛЛЛ041B, "All POST request headers:");
    for (Header header : bььь044Cь044C.getAllHeaders()) {
        Log.d(b041BЛЛЛЛ041B, header.getName() + NetworkUtils.DELIMITER_COLON + header.getValue());
    }
    Log.d(b041BЛЛЛЛ041B, "HTTP Request body: " + str4);
    String str5 = b041BЛЛЛЛ041B;
    StringBuilder append = new StringBuilder().append("HTTP Response: ");
    StatusLine statusLine = execute.getStatusLine();
    int b0427ЧЧЧ0427Ч = b0427ЧЧЧ0427Ч();
    switch ((b0427ЧЧЧ0427Ч * (b04270427ЧЧ0427Ч + b0427ЧЧЧ0427Ч)) % bЧЧ0427Ч0427Ч) {
        case 0:
            break;
        default:
            b0427Ч0427Ч0427Ч = b0427ЧЧЧ0427Ч();
            bЧ0427ЧЧ0427Ч = b0427ЧЧЧ0427Ч();
            break;
    }
    Log.d(str5, append.append(statusLine.toString()).toString());
    Log.d(b041BЛЛЛЛ041B, "HTTP Response: " + EntityUtils.toString(execute.getEntity()));
    return execute.getStatusLine().getStatusCode() == 200;
}
项目:calcite-avatica    文件:AvaticaCommonsHttpClientImplTest.java   
@Test public void testRetryOnHttp503() throws Exception {
  final byte[] requestBytes = "fake_request".getBytes(UTF_8);
  final CloseableHttpResponse badResponse = mock(CloseableHttpResponse.class);
  final CloseableHttpResponse goodResponse = mock(CloseableHttpResponse.class);
  final StatusLine badStatusLine = mock(StatusLine.class);
  final StatusLine goodStatusLine = mock(StatusLine.class);
  final StringEntity responseEntity = new StringEntity("success");
  final Answer<CloseableHttpResponse> failThenSucceed = new Answer<CloseableHttpResponse>() {
    private int iteration = 0;
    @Override public CloseableHttpResponse answer(InvocationOnMock invocation) throws Throwable {
      iteration++;
      if (1 == iteration) {
        return badResponse;
      } else {
        return goodResponse;
      }
    }
  };

  final AvaticaCommonsHttpClientImpl client = mock(AvaticaCommonsHttpClientImpl.class);

  when(client.send(any(byte[].class))).thenCallRealMethod();
  when(client.execute(any(HttpPost.class), any(HttpClientContext.class))).then(failThenSucceed);

  when(badResponse.getStatusLine()).thenReturn(badStatusLine);
  when(badStatusLine.getStatusCode()).thenReturn(HttpURLConnection.HTTP_UNAVAILABLE);

  when(goodResponse.getStatusLine()).thenReturn(goodStatusLine);
  when(goodStatusLine.getStatusCode()).thenReturn(HttpURLConnection.HTTP_OK);
  when(goodResponse.getEntity()).thenReturn(responseEntity);

  byte[] responseBytes = client.send(requestBytes);
  assertEquals("success", new String(responseBytes, UTF_8));
}