类org.apache.http.message.BasicHttpResponse源码实例Demo

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

源代码1 项目: djl-demo   文件: RequestHandler.java
/** Handles URLs predicted as malicious. */
private void blockedMaliciousSiteRequested() {
    try {
        HttpResponse response =
                new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_BAD_REQUEST, "MAL");
        HttpEntity httpEntity = new FileEntity(new File("index.html"), ContentType.WILDCARD);
        BufferedWriter bufferedWriter =
                new BufferedWriter(new OutputStreamWriter(clientSocket.getOutputStream()));
        bufferedWriter.write(response.getStatusLine().toString());
        String headers =
                "Proxy-agent: FilterProxy/1.0\r\n"
                        + httpEntity.getContentType().toString()
                        + "\r\n"
                        + "Content-Length: "
                        + httpEntity.getContentLength()
                        + "\r\n\r\n";
        bufferedWriter.write(headers);
        // Pass index.html content
        bufferedWriter.write(EntityUtils.toString(httpEntity));
        bufferedWriter.flush();
        bufferedWriter.close();
    } catch (IOException e) {
        logger.error("Error writing to client when requested a blocked site", e);
    }
}
 
源代码2 项目: esigate   文件: DriverTest.java
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"));
}
 
源代码3 项目: esigate   文件: HttpClientRequestExecutorTest.java
/**
 * 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
    }
}
 
源代码4 项目: docker-java-api   文件: AssertRequestTestCase.java
/**
 * 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)
    );
}
 
@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();
}
 
@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());
    }
}
 
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;
}
 
源代码8 项目: nexus-repository-conan   文件: ConanClient.java
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;
  }
}
 
源代码9 项目: jus   文件: VolleyRequestPipeline.java
@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;
}
 
源代码10 项目: esigate   文件: DriverTest.java
/**
 * 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());
}
 
源代码11 项目: esigate   文件: DriverTest.java
/**
 * 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);
}
 
源代码12 项目: SaveVolley   文件: BasicNetworkTest.java
@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));
}
 
源代码13 项目: SaveVolley   文件: BasicNetworkTest.java
@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));
}
 
源代码14 项目: SaveVolley   文件: BasicNetworkTest.java
@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);
    }
}
 
源代码15 项目: SaveVolley   文件: BasicNetworkTest.java
@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);
    }
}
 
源代码16 项目: SaveVolley   文件: BasicNetworkTest.java
@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);
    }
}
 
源代码17 项目: SaveVolley   文件: BasicNetworkTest.java
@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);
    }
}
 
源代码18 项目: cukes   文件: HttpAssertionFacadeImplTest.java
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;
}
 
源代码19 项目: esigate   文件: HttpClientRequestExecutorTest.java
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;
}
 
源代码20 项目: esigate   文件: DriverTest.java
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());
}
 
源代码21 项目: product-emm   文件: BasicNetworkTest.java
@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));
}
 
源代码22 项目: product-emm   文件: BasicNetworkTest.java
@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));
}
 
源代码23 项目: product-emm   文件: BasicNetworkTest.java
@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);
    }
}
 
源代码24 项目: product-emm   文件: BasicNetworkTest.java
@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);
    }
}
 
源代码25 项目: product-emm   文件: BasicNetworkTest.java
@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);
    }
}
 
源代码26 项目: product-emm   文件: BasicNetworkTest.java
@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);
    }
}
 
源代码27 项目: esigate   文件: DriverTest.java
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));
}
 
源代码28 项目: product-emm   文件: BasicNetworkTest.java
@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));
}
 
源代码29 项目: product-emm   文件: BasicNetworkTest.java
@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);
    }
}
 
源代码30 项目: product-emm   文件: BasicNetworkTest.java
@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);
    }
}
 
 类所在包
 同包方法