下面列出了org.apache.http.impl.conn.ProxySelectorRoutePlanner#org.apache.http.message.BasicHttpResponse 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/** 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);
}
}
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"));
}
/**
* 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
}
}
/**
* 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;
}
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;
}
}
@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;
}
/**
* 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());
}
/**
* 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);
}
@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));
}
@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));
}
@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);
}
}
@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);
}
}
@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);
}
}
@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);
}
}
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;
}
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;
}
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());
}
@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));
}
@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));
}
@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);
}
}
@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);
}
}
@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);
}
}
@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);
}
}
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));
}
@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));
}
@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);
}
}
@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);
}
}