org.apache.http.message.BasicHttpResponse Java Examples

The following examples show how to use org.apache.http.message.BasicHttpResponse. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ConanClient.java    From nexus-repository-conan with Eclipse Public License 1.0 7 votes vote down vote up
public HttpResponse getHttpResponse(final String path) throws IOException {
  try (CloseableHttpResponse closeableHttpResponse = super.get(path)) {
    HttpEntity entity = closeableHttpResponse.getEntity();

    BasicHttpEntity basicHttpEntity = new BasicHttpEntity();
    String content = EntityUtils.toString(entity);
    basicHttpEntity.setContent(IOUtils.toInputStream(content));

    basicHttpEntity.setContentEncoding(entity.getContentEncoding());
    basicHttpEntity.setContentLength(entity.getContentLength());
    basicHttpEntity.setContentType(entity.getContentType());
    basicHttpEntity.setChunked(entity.isChunked());

    StatusLine statusLine = closeableHttpResponse.getStatusLine();
    HttpResponse response = new BasicHttpResponse(statusLine);
    response.setEntity(basicHttpEntity);
    response.setHeaders(closeableHttpResponse.getAllHeaders());
    response.setLocale(closeableHttpResponse.getLocale());
    return response;
  }
}
 
Example #2
Source File: HttpAssertionFacadeImplTest.java    From cukes with Apache License 2.0 6 votes vote down vote up
private Response generateResponse(String contentType, int status, byte[] content) {
    final BasicStatusLine statusLine = new BasicStatusLine(
        new ProtocolVersion("HTTP", 1, 1),
        status,
        EnglishReasonPhraseCatalog.INSTANCE.getReason(status, Locale.ENGLISH));

    final BasicHttpResponse httpResponse = new BasicHttpResponse(statusLine);
    httpResponse.addHeader("Content-Type", contentType);

    final HttpResponseDecorator httpResponseDecorator = new HttpResponseDecorator(httpResponse, content);
    final RestAssuredResponseImpl restResponse = new RestAssuredResponseImpl();
    restResponse.setStatusCode(status);
    restResponse.parseResponse(
        httpResponseDecorator,
        content,
        false,
        new ResponseParserRegistrar()
    );

    return restResponse;
}
 
Example #3
Source File: VolleyRequestPipeline.java    From jus with Apache License 2.0 6 votes vote down vote up
@Override
public RequestPipeline prepare(States.GenericState state) {
    NetworkResponse resp =  Util.newResponse(state);
    HttpResponse vResp = new BasicHttpResponse(new ProtocolVersion("HTTP", 1, 1),
            resp.statusCode, "OK");
    vResp.setEntity(new ByteArrayEntity(resp.data));
    for(String h:resp.headers.names()) {
        vResp.setHeader(h,resp.headers.get(h));
    }
    MockVolleyHttpStack stack = new MockVolleyHttpStack();
    stack.setResponseToReturn(vResp);
    this.requestQueue = new com.android.volley.RequestQueue(
            new VolleyNoCache(),
            new BasicNetwork(stack),
            state.concurrencyLevel
    );
    requestQueue.start();
    return this;
}
 
Example #4
Source File: DriverTest.java    From esigate with Apache License 2.0 6 votes vote down vote up
/**
 * 0000174: Redirect location with default port specified are incorrectly rewritten when preserveHost=true
 * <p>
 * http://www.esigate.org/mantisbt/view.php?id=174
 * 
 * <p>
 * Issue with default ports, which results in invalid url creation.
 * 
 * @throws Exception
 */
public void testRewriteRedirectResponseWithDefaultPortSpecifiedInLocation() throws Exception {
    // Conf
    Properties properties = new PropertiesBuilder() //
            .set(Parameters.REMOTE_URL_BASE, "http://www.foo.com:8080") //
            .set(Parameters.PRESERVE_HOST, true) //
            .build();

    HttpResponse response =
            new BasicHttpResponse(new ProtocolVersion("HTTP", 1, 1), HttpStatus.SC_MOVED_TEMPORARILY, "Found");
    // The backend server sets the port even if default (OK it should not
    // but some servers do it)
    response.addHeader("Location", "http://www.foo.com:80/foo/bar");
    mockConnectionManager.setResponse(response);
    Driver driver = createMockDriver(properties, mockConnectionManager);
    request = TestUtils.createIncomingRequest("http://www.foo.com:80/foo");
    // HttpClientHelper will use the Host
    // header to rewrite the request sent to the backend
    // http://www.foo.com/foo
    CloseableHttpResponse driverResponse = driver.proxy("/foo", request.build());
    // The test initially failed with an invalid Location:
    // http://www.foo.com:80:80/foo/bar
    assertEquals("http://www.foo.com:80/foo/bar", driverResponse.getFirstHeader("Location").getValue());
}
 
Example #5
Source File: GenericApiGatewayClientTest.java    From apigateway-generic-java-sdk with Apache License 2.0 6 votes vote down vote up
@Test
public void testExecute_non2xx_exception() throws IOException {
    HttpResponse resp = new BasicHttpResponse(new BasicStatusLine(HttpVersion.HTTP_1_1, 404, "Not found"));
    BasicHttpEntity entity = new BasicHttpEntity();
    entity.setContent(new ByteArrayInputStream("{\"message\" : \"error payload\"}".getBytes()));
    resp.setEntity(entity);
    Mockito.doReturn(resp).when(mockClient).execute(any(HttpUriRequest.class), any(HttpContext.class));

    Map<String, String> headers = new HashMap<>();
    headers.put("Account-Id", "fubar");
    headers.put("Content-Type", "application/json");

    try {
        client.execute(
                new GenericApiGatewayRequestBuilder()
                        .withBody(new ByteArrayInputStream("test request".getBytes()))
                        .withHttpMethod(HttpMethodName.POST)
                        .withHeaders(headers)
                        .withResourcePath("/test/orders").build());

        Assert.fail("Expected exception");
    } catch (GenericApiGatewayException e) {
        assertEquals("Wrong status code", 404, e.getStatusCode());
        assertEquals("Wrong exception message", "{\"message\":\"error payload\"}", e.getErrorMessage());
    }
}
 
Example #6
Source File: AssertRequestTestCase.java    From docker-java-api with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * Should return the given response if the request meets the given
 * condition.
 * 
 * @throws Exception Unexpected.
 */
@Test
public void returnResponseIfRequestMeetsCondition() throws Exception {
    final HttpResponse response = new BasicHttpResponse(
        new BasicStatusLine(
            new ProtocolVersion("HTTP", 1, 1), HttpStatus.SC_OK, "OK"
        )
    );
    MatcherAssert.assertThat(
        new AssertRequest(
            response,
            new Condition(
                "",
                // @checkstyle LineLength (1 line)
                r -> "http://some.test.com".equals(r.getRequestLine().getUri())
            )
        ).execute(new HttpGet("http://some.test.com")),
        Matchers.is(response)
    );
}
 
Example #7
Source File: TracedResponseHandlerTest.java    From aws-xray-sdk-java with Apache License 2.0 6 votes vote down vote up
private Segment segmentInResponseToCode(int code) {
    NoOpResponseHandler responseHandler = new NoOpResponseHandler();
    TracedResponseHandler<String> tracedResponseHandler = new TracedResponseHandler<>(responseHandler);
    HttpResponse httpResponse = new BasicHttpResponse(new BasicStatusLine(HttpVersion.HTTP_1_1, code, ""));

    Segment segment = AWSXRay.beginSegment("test");
    AWSXRay.beginSubsegment("someHttpCall");

    try {
        tracedResponseHandler.handleResponse(httpResponse);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }

    AWSXRay.endSubsegment();
    AWSXRay.endSegment();
    return segment;
}
 
Example #8
Source File: HttpClientRequestExecutorTest.java    From esigate with Apache License 2.0 6 votes vote down vote up
/**
 * Test that we don't have a NullpointerException when forcing the caching (ttl).
 * 
 * @throws Exception
 */
public void testForcedTtlWith304ResponseCode() throws Exception {
    properties = new PropertiesBuilder() //
            .set(Parameters.REMOTE_URL_BASE, "http://localhost:8080") //
            .set(Parameters.TTL, 1000) // Default value
            .build();

    createHttpClientRequestExecutor();
    DriverRequest originalRequest = TestUtils.createDriverRequest(driver);
    originalRequest.getOriginalRequest().addHeader("If-Modified-Since", "Fri, 15 Jun 2012 21:06:25 GMT");
    OutgoingRequest request =
            httpClientRequestExecutor.createOutgoingRequest(originalRequest, "http://localhost:8080", false);
    HttpResponse response =
            new BasicHttpResponse(new BasicStatusLine(new ProtocolVersion("HTTP", 1, 1),
                    HttpStatus.SC_NOT_MODIFIED, "Not Modified"));
    mockConnectionManager.setResponse(response);
    HttpResponse result = httpClientRequestExecutor.execute(request);
    if (result.getEntity() != null) {
        result.getEntity().writeTo(new NullOutputStream());
        // We should have had a NullpointerException
    }
}
 
Example #9
Source File: GenericApiGatewayClientTest.java    From apigateway-generic-java-sdk with Apache License 2.0 6 votes vote down vote up
@Before
public void setUp() throws IOException {
    AWSCredentialsProvider credentials = new AWSStaticCredentialsProvider(new BasicAWSCredentials("foo", "bar"));

    mockClient = Mockito.mock(SdkHttpClient.class);
    HttpResponse resp = new BasicHttpResponse(new BasicStatusLine(HttpVersion.HTTP_1_1, 200, "OK"));
    BasicHttpEntity entity = new BasicHttpEntity();
    entity.setContent(new ByteArrayInputStream("test payload".getBytes()));
    resp.setEntity(entity);
    Mockito.doReturn(resp).when(mockClient).execute(any(HttpUriRequest.class), any(HttpContext.class));

    ClientConfiguration clientConfig = new ClientConfiguration();

    client = new GenericApiGatewayClientBuilder()
            .withClientConfiguration(clientConfig)
            .withCredentials(credentials)
            .withEndpoint("https://foobar.execute-api.us-east-1.amazonaws.com")
            .withRegion(Region.getRegion(Regions.fromName("us-east-1")))
            .withApiKey("12345")
            .withHttpClient(new AmazonHttpClient(clientConfig, mockClient, null))
            .build();
}
 
Example #10
Source File: DriverTest.java    From esigate with Apache License 2.0 6 votes vote down vote up
/**
 * 0000161: Cookie domain validation too strict with preserveHost.
 * 
 * @see <a href="http://www.esigate.org/mantisbt/view.php?id=161">0000161</a>
 * 
 * @throws Exception
 */
public void testBug161SetCookie() throws Exception {
    // Conf
    Properties properties = new PropertiesBuilder() //
            .set(Parameters.REMOTE_URL_BASE, "http://localhost/") //
            .set(Parameters.PRESERVE_HOST, true) //
            .build();

    BasicHttpResponse response = new BasicHttpResponse(new ProtocolVersion("HTTP", 1, 1), HttpStatus.SC_OK, "Ok");
    response.addHeader("Date", "Thu, 13 Dec 2012 08:55:37 GMT");
    response.addHeader("Set-Cookie", "mycookie=123456; domain=.mydomain.fr; path=/");
    response.setEntity(new StringEntity("test"));
    mockConnectionManager.setResponse(response);

    Driver driver = createMockDriver(properties, mockConnectionManager);

    request = TestUtils.createIncomingRequest("http://test.mydomain.fr/foobar/");

    IncomingRequest incomingRequest = request.build();

    driver.proxy("/foobar/", incomingRequest);

    assertTrue("Set-Cookie must be forwarded.", incomingRequest.getNewCookies().length > 0);
}
 
Example #11
Source File: BasicNetworkTest.java    From SaveVolley with Apache License 2.0 6 votes vote down vote up
@Test public void unauthorized() throws Exception {
    MockHttpStack mockHttpStack = new MockHttpStack();
    BasicHttpResponse fakeResponse = new BasicHttpResponse(new ProtocolVersion("HTTP", 1, 1),
            401, "Unauthorized");
    mockHttpStack.setResponseToReturn(fakeResponse);
    BasicNetwork httpNetwork = new BasicNetwork(mockHttpStack);
    Request<String> request = buildRequest();
    request.setRetryPolicy(mMockRetryPolicy);
    doThrow(new VolleyError()).when(mMockRetryPolicy).retry(any(VolleyError.class));
    try {
        httpNetwork.performRequest(request);
    } catch (VolleyError e) {
        // expected
    }
    // should retry in case it's an auth failure.
    verify(mMockRetryPolicy).retry(any(AuthFailureError.class));
}
 
Example #12
Source File: BasicNetworkTest.java    From SaveVolley with Apache License 2.0 6 votes vote down vote up
@Test public void forbidden() throws Exception {
    MockHttpStack mockHttpStack = new MockHttpStack();
    BasicHttpResponse fakeResponse = new BasicHttpResponse(new ProtocolVersion("HTTP", 1, 1),
            403, "Forbidden");
    mockHttpStack.setResponseToReturn(fakeResponse);
    BasicNetwork httpNetwork = new BasicNetwork(mockHttpStack);
    Request<String> request = buildRequest();
    request.setRetryPolicy(mMockRetryPolicy);
    doThrow(new VolleyError()).when(mMockRetryPolicy).retry(any(VolleyError.class));
    try {
        httpNetwork.performRequest(request);
    } catch (VolleyError e) {
        // expected
    }
    // should retry in case it's an auth failure.
    verify(mMockRetryPolicy).retry(any(AuthFailureError.class));
}
 
Example #13
Source File: BasicNetworkTest.java    From SaveVolley with Apache License 2.0 6 votes vote down vote up
@Test public void redirect() throws Exception {
    for (int i = 300; i <= 399; i++) {
        MockHttpStack mockHttpStack = new MockHttpStack();
        BasicHttpResponse fakeResponse = new BasicHttpResponse(
                new ProtocolVersion("HTTP", 1, 1), i, "");
        mockHttpStack.setResponseToReturn(fakeResponse);
        BasicNetwork httpNetwork = new BasicNetwork(mockHttpStack);
        Request<String> request = buildRequest();
        request.setRetryPolicy(mMockRetryPolicy);
        doThrow(new VolleyError()).when(mMockRetryPolicy).retry(any(VolleyError.class));
        try {
            httpNetwork.performRequest(request);
        } catch (VolleyError e) {
            // expected
        }
        // should not retry 300 responses.
        verify(mMockRetryPolicy, never()).retry(any(VolleyError.class));
        reset(mMockRetryPolicy);
    }
}
 
Example #14
Source File: BasicNetworkTest.java    From SaveVolley with Apache License 2.0 6 votes vote down vote up
@Test public void otherClientError() throws Exception {
    for (int i = 400; i <= 499; i++) {
        if (i == 401 || i == 403) {
            // covered above.
            continue;
        }
        MockHttpStack mockHttpStack = new MockHttpStack();
        BasicHttpResponse fakeResponse = new BasicHttpResponse(
                new ProtocolVersion("HTTP", 1, 1), i, "");
        mockHttpStack.setResponseToReturn(fakeResponse);
        BasicNetwork httpNetwork = new BasicNetwork(mockHttpStack);
        Request<String> request = buildRequest();
        request.setRetryPolicy(mMockRetryPolicy);
        doThrow(new VolleyError()).when(mMockRetryPolicy).retry(any(VolleyError.class));
        try {
            httpNetwork.performRequest(request);
        } catch (VolleyError e) {
            // expected
        }
        // should not retry other 400 errors.
        verify(mMockRetryPolicy, never()).retry(any(VolleyError.class));
        reset(mMockRetryPolicy);
    }
}
 
Example #15
Source File: BasicNetworkTest.java    From SaveVolley with Apache License 2.0 6 votes vote down vote up
@Test public void serverError_enableRetries() throws Exception {
    for (int i = 500; i <= 599; i++) {
        MockHttpStack mockHttpStack = new MockHttpStack();
        BasicHttpResponse fakeResponse = new BasicHttpResponse(
                new ProtocolVersion("HTTP", 1, 1), i, "");
        mockHttpStack.setResponseToReturn(fakeResponse);
        BasicNetwork httpNetwork = new BasicNetwork(mockHttpStack, new ByteArrayPool(4096));
        Request<String> request = buildRequest();
        request.setRetryPolicy(mMockRetryPolicy);
        request.setShouldRetryServerErrors(true);
        doThrow(new VolleyError()).when(mMockRetryPolicy).retry(any(VolleyError.class));
        try {
            httpNetwork.performRequest(request);
        } catch (VolleyError e) {
            // expected
        }
        // should retry all 500 errors
        verify(mMockRetryPolicy).retry(any(ServerError.class));
        reset(mMockRetryPolicy);
    }
}
 
Example #16
Source File: BasicNetworkTest.java    From SaveVolley with Apache License 2.0 6 votes vote down vote up
@Test public void serverError_disableRetries() throws Exception {
    for (int i = 500; i <= 599; i++) {
        MockHttpStack mockHttpStack = new MockHttpStack();
        BasicHttpResponse fakeResponse = new BasicHttpResponse(
                new ProtocolVersion("HTTP", 1, 1), i, "");
        mockHttpStack.setResponseToReturn(fakeResponse);
        BasicNetwork httpNetwork = new BasicNetwork(mockHttpStack);
        Request<String> request = buildRequest();
        request.setRetryPolicy(mMockRetryPolicy);
        doThrow(new VolleyError()).when(mMockRetryPolicy).retry(any(VolleyError.class));
        try {
            httpNetwork.performRequest(request);
        } catch (VolleyError e) {
            // expected
        }
        // should not retry any 500 error w/ HTTP 500 retries turned off (the default).
        verify(mMockRetryPolicy, never()).retry(any(VolleyError.class));
        reset(mMockRetryPolicy);
    }
}
 
Example #17
Source File: DriverTest.java    From esigate with Apache License 2.0 6 votes vote down vote up
public void testHeadersFilteredWhenError500() throws Exception {
    Properties properties = new Properties();
    properties.put(Parameters.REMOTE_URL_BASE.getName(), "http://localhost");
    HttpResponse response =
            new BasicHttpResponse(new ProtocolVersion("HTTP", 1, 1), HttpStatus.SC_INTERNAL_SERVER_ERROR,
                    "Internal Server Error");
    response.addHeader("Content-type", "Text/html;Charset=UTF-8");
    response.addHeader("Transfer-Encoding", "dummy");
    HttpEntity httpEntity = new StringEntity("Error", "UTF-8");
    response.setEntity(httpEntity);
    mockConnectionManager.setResponse(response);
    Driver driver = createMockDriver(properties, mockConnectionManager);
    CloseableHttpResponse driverResponse;
    try {
        driverResponse = driver.proxy("/", request.build());
        fail("We should get an HttpErrorPage");
    } catch (HttpErrorPage e) {
        driverResponse = e.getHttpResponse();
    }
    int statusCode = driverResponse.getStatusLine().getStatusCode();
    assertEquals("Status code", HttpStatus.SC_INTERNAL_SERVER_ERROR, statusCode);
    assertFalse("Header 'Transfer-Encoding'", driverResponse.containsHeader("Transfer-Encoding"));
}
 
Example #18
Source File: HttpClientRequestExecutorTest.java    From esigate with Apache License 2.0 6 votes vote down vote up
private HttpResponse createMockGzippedResponse(String content) throws IOException {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    GZIPOutputStream gzos = new GZIPOutputStream(baos);
    byte[] uncompressedBytes = content.getBytes();
    gzos.write(uncompressedBytes, 0, uncompressedBytes.length);
    gzos.close();
    byte[] compressedBytes = baos.toByteArray();
    ByteArrayEntity httpEntity = new ByteArrayEntity(compressedBytes);
    httpEntity.setContentType("text/html; charset=ISO-8859-1");
    httpEntity.setContentEncoding("gzip");
    StatusLine statusLine = new BasicStatusLine(new ProtocolVersion("p", 1, 2), HttpStatus.SC_OK, "OK");
    BasicHttpResponse httpResponse = new BasicHttpResponse(statusLine);
    httpResponse.addHeader("Content-type", "text/html; charset=ISO-8859-1");
    httpResponse.addHeader("Content-encoding", "gzip");
    httpResponse.setEntity(httpEntity);
    return httpResponse;
}
 
Example #19
Source File: DriverTest.java    From esigate with Apache License 2.0 6 votes vote down vote up
public void testRewriteCookiePathNotMatching() throws Exception {
    Properties properties = new Properties();
    properties.put(Parameters.REMOTE_URL_BASE.getName(), "http://localhost:8080/");
    properties.put(Parameters.PRESERVE_HOST.getName(), "true");

    mockConnectionManager = new MockConnectionManager() {
        @Override
        public HttpResponse execute(HttpRequest httpRequest) {
            BasicHttpResponse response =
                    new BasicHttpResponse(new ProtocolVersion("HTTP", 1, 1), HttpStatus.SC_OK, "OK");
            response.addHeader(new BasicHeader("Set-Cookie", "name1=value1;Path=/bar"));
            return response;
        }
    };

    Driver driver = createMockDriver(properties, mockConnectionManager);

    request = TestUtils.createIncomingRequest("http://localhost:8081/foo/foobar.jsp");

    IncomingRequest incomingRequest = request.build();

    driver.proxy("/bar/foobar.jsp", incomingRequest);

    Assert.assertEquals(1, incomingRequest.getNewCookies().length);
    Assert.assertEquals("/", incomingRequest.getNewCookies()[0].getPath());
}
 
Example #20
Source File: BasicNetworkTest.java    From product-emm with Apache License 2.0 6 votes vote down vote up
@Test public void unauthorized() throws Exception {
    MockHttpStack mockHttpStack = new MockHttpStack();
    BasicHttpResponse fakeResponse = new BasicHttpResponse(new ProtocolVersion("HTTP", 1, 1),
            401, "Unauthorized");
    mockHttpStack.setResponseToReturn(fakeResponse);
    BasicNetwork httpNetwork = new BasicNetwork(mockHttpStack);
    Request<String> request = buildRequest();
    request.setRetryPolicy(mMockRetryPolicy);
    doThrow(new VolleyError()).when(mMockRetryPolicy).retry(any(VolleyError.class));
    try {
        httpNetwork.performRequest(request);
    } catch (VolleyError e) {
        // expected
    }
    // should retry in case it's an auth failure.
    verify(mMockRetryPolicy).retry(any(AuthFailureError.class));
}
 
Example #21
Source File: BasicNetworkTest.java    From product-emm with Apache License 2.0 6 votes vote down vote up
@Test public void forbidden() throws Exception {
    MockHttpStack mockHttpStack = new MockHttpStack();
    BasicHttpResponse fakeResponse = new BasicHttpResponse(new ProtocolVersion("HTTP", 1, 1),
            403, "Forbidden");
    mockHttpStack.setResponseToReturn(fakeResponse);
    BasicNetwork httpNetwork = new BasicNetwork(mockHttpStack);
    Request<String> request = buildRequest();
    request.setRetryPolicy(mMockRetryPolicy);
    doThrow(new VolleyError()).when(mMockRetryPolicy).retry(any(VolleyError.class));
    try {
        httpNetwork.performRequest(request);
    } catch (VolleyError e) {
        // expected
    }
    // should retry in case it's an auth failure.
    verify(mMockRetryPolicy).retry(any(AuthFailureError.class));
}
 
Example #22
Source File: BasicNetworkTest.java    From product-emm with Apache License 2.0 6 votes vote down vote up
@Test public void redirect() throws Exception {
    for (int i = 300; i <= 399; i++) {
        MockHttpStack mockHttpStack = new MockHttpStack();
        BasicHttpResponse fakeResponse =
                new BasicHttpResponse(new ProtocolVersion("HTTP", 1, 1), i, "");
        mockHttpStack.setResponseToReturn(fakeResponse);
        BasicNetwork httpNetwork = new BasicNetwork(mockHttpStack);
        Request<String> request = buildRequest();
        request.setRetryPolicy(mMockRetryPolicy);
        doThrow(new VolleyError()).when(mMockRetryPolicy).retry(any(VolleyError.class));
        try {
            httpNetwork.performRequest(request);
        } catch (VolleyError e) {
            // expected
        }
        // should not retry 300 responses.
        verify(mMockRetryPolicy, never()).retry(any(VolleyError.class));
        reset(mMockRetryPolicy);
    }
}
 
Example #23
Source File: BasicNetworkTest.java    From product-emm with Apache License 2.0 6 votes vote down vote up
@Test public void otherClientError() throws Exception {
    for (int i = 400; i <= 499; i++) {
        if (i == 401 || i == 403) {
            // covered above.
            continue;
        }
        MockHttpStack mockHttpStack = new MockHttpStack();
        BasicHttpResponse fakeResponse =
                new BasicHttpResponse(new ProtocolVersion("HTTP", 1, 1), i, "");
        mockHttpStack.setResponseToReturn(fakeResponse);
        BasicNetwork httpNetwork = new BasicNetwork(mockHttpStack);
        Request<String> request = buildRequest();
        request.setRetryPolicy(mMockRetryPolicy);
        doThrow(new VolleyError()).when(mMockRetryPolicy).retry(any(VolleyError.class));
        try {
            httpNetwork.performRequest(request);
        } catch (VolleyError e) {
            // expected
        }
        // should not retry other 400 errors.
        verify(mMockRetryPolicy, never()).retry(any(VolleyError.class));
        reset(mMockRetryPolicy);
    }
}
 
Example #24
Source File: BasicNetworkTest.java    From product-emm with Apache License 2.0 6 votes vote down vote up
@Test public void serverError_enableRetries() throws Exception {
    for (int i = 500; i <= 599; i++) {
        MockHttpStack mockHttpStack = new MockHttpStack();
        BasicHttpResponse fakeResponse =
                new BasicHttpResponse(new ProtocolVersion("HTTP", 1, 1), i, "");
        mockHttpStack.setResponseToReturn(fakeResponse);
        BasicNetwork httpNetwork =
                new BasicNetwork(mockHttpStack, new ByteArrayPool(4096));
        Request<String> request = buildRequest();
        request.setRetryPolicy(mMockRetryPolicy);
        request.setShouldRetryServerErrors(true);
        doThrow(new VolleyError()).when(mMockRetryPolicy).retry(any(VolleyError.class));
        try {
            httpNetwork.performRequest(request);
        } catch (VolleyError e) {
            // expected
        }
        // should retry all 500 errors
        verify(mMockRetryPolicy).retry(any(ServerError.class));
        reset(mMockRetryPolicy);
    }
}
 
Example #25
Source File: BasicNetworkTest.java    From product-emm with Apache License 2.0 6 votes vote down vote up
@Test public void serverError_disableRetries() throws Exception {
    for (int i = 500; i <= 599; i++) {
        MockHttpStack mockHttpStack = new MockHttpStack();
        BasicHttpResponse fakeResponse =
                new BasicHttpResponse(new ProtocolVersion("HTTP", 1, 1), i, "");
        mockHttpStack.setResponseToReturn(fakeResponse);
        BasicNetwork httpNetwork = new BasicNetwork(mockHttpStack);
        Request<String> request = buildRequest();
        request.setRetryPolicy(mMockRetryPolicy);
        doThrow(new VolleyError()).when(mMockRetryPolicy).retry(any(VolleyError.class));
        try {
            httpNetwork.performRequest(request);
        } catch (VolleyError e) {
            // expected
        }
        // should not retry any 500 error w/ HTTP 500 retries turned off (the default).
        verify(mMockRetryPolicy, never()).retry(any(VolleyError.class));
        reset(mMockRetryPolicy);
    }
}
 
Example #26
Source File: DriverTest.java    From esigate with Apache License 2.0 6 votes vote down vote up
public void testSpecialCharacterInErrorPage() throws Exception {
    Properties properties = new Properties();
    properties.put(Parameters.REMOTE_URL_BASE.getName(), "http://localhost");
    HttpResponse response =
            new BasicHttpResponse(new ProtocolVersion("HTTP", 1, 1), HttpStatus.SC_INTERNAL_SERVER_ERROR,
                    "Internal Server Error");
    response.addHeader("Content-type", "Text/html;Charset=UTF-8");
    HttpEntity httpEntity = new StringEntity("é", "UTF-8");
    response.setEntity(httpEntity);
    mockConnectionManager.setResponse(response);
    Driver driver = createMockDriver(properties, mockConnectionManager);
    CloseableHttpResponse driverResponse;
    try {
        driverResponse = driver.proxy("/", request.build());
        fail("We should get an HttpErrorPage");
    } catch (HttpErrorPage e) {
        driverResponse = e.getHttpResponse();
    }
    assertEquals("é", HttpResponseUtils.toString(driverResponse));
}
 
Example #27
Source File: BasicNetworkTest.java    From product-emm with Apache License 2.0 6 votes vote down vote up
@Test public void forbidden() throws Exception {
    MockHttpStack mockHttpStack = new MockHttpStack();
    BasicHttpResponse fakeResponse = new BasicHttpResponse(new ProtocolVersion("HTTP", 1, 1),
            403, "Forbidden");
    mockHttpStack.setResponseToReturn(fakeResponse);
    BasicNetwork httpNetwork = new BasicNetwork(mockHttpStack);
    Request<String> request = buildRequest();
    request.setRetryPolicy(mMockRetryPolicy);
    doThrow(new VolleyError()).when(mMockRetryPolicy).retry(any(VolleyError.class));
    try {
        httpNetwork.performRequest(request);
    } catch (VolleyError e) {
        // expected
    }
    // should retry in case it's an auth failure.
    verify(mMockRetryPolicy).retry(any(AuthFailureError.class));
}
 
Example #28
Source File: BasicNetworkTest.java    From product-emm with Apache License 2.0 6 votes vote down vote up
@Test public void redirect() throws Exception {
    for (int i = 300; i <= 399; i++) {
        MockHttpStack mockHttpStack = new MockHttpStack();
        BasicHttpResponse fakeResponse =
                new BasicHttpResponse(new ProtocolVersion("HTTP", 1, 1), i, "");
        mockHttpStack.setResponseToReturn(fakeResponse);
        BasicNetwork httpNetwork = new BasicNetwork(mockHttpStack);
        Request<String> request = buildRequest();
        request.setRetryPolicy(mMockRetryPolicy);
        doThrow(new VolleyError()).when(mMockRetryPolicy).retry(any(VolleyError.class));
        try {
            httpNetwork.performRequest(request);
        } catch (VolleyError e) {
            // expected
        }
        // should not retry 300 responses.
        verify(mMockRetryPolicy, never()).retry(any(VolleyError.class));
        reset(mMockRetryPolicy);
    }
}
 
Example #29
Source File: BasicNetworkTest.java    From product-emm with Apache License 2.0 6 votes vote down vote up
@Test public void serverError_disableRetries() throws Exception {
    for (int i = 500; i <= 599; i++) {
        MockHttpStack mockHttpStack = new MockHttpStack();
        BasicHttpResponse fakeResponse =
                new BasicHttpResponse(new ProtocolVersion("HTTP", 1, 1), i, "");
        mockHttpStack.setResponseToReturn(fakeResponse);
        BasicNetwork httpNetwork = new BasicNetwork(mockHttpStack);
        Request<String> request = buildRequest();
        request.setRetryPolicy(mMockRetryPolicy);
        doThrow(new VolleyError()).when(mMockRetryPolicy).retry(any(VolleyError.class));
        try {
            httpNetwork.performRequest(request);
        } catch (VolleyError e) {
            // expected
        }
        // should not retry any 500 error w/ HTTP 500 retries turned off (the default).
        verify(mMockRetryPolicy, never()).retry(any(VolleyError.class));
        reset(mMockRetryPolicy);
    }
}
 
Example #30
Source File: MockHttpClient.java    From google-http-java-client with Apache License 2.0 6 votes vote down vote up
@Override
protected RequestDirector createClientRequestDirector(
    HttpRequestExecutor requestExec,
    ClientConnectionManager conman,
    ConnectionReuseStrategy reustrat,
    ConnectionKeepAliveStrategy kastrat,
    HttpRoutePlanner rouplan,
    HttpProcessor httpProcessor,
    HttpRequestRetryHandler retryHandler,
    RedirectHandler redirectHandler,
    AuthenticationHandler targetAuthHandler,
    AuthenticationHandler proxyAuthHandler,
    UserTokenHandler stateHandler,
    HttpParams params) {
  return new RequestDirector() {
    @Beta
    public HttpResponse execute(HttpHost target, HttpRequest request, HttpContext context)
        throws HttpException, IOException {
      return new BasicHttpResponse(HttpVersion.HTTP_1_1, responseCode, null);
    }
  };
}