下面列出了怎么用org.apache.http.ProtocolVersion的API类实例代码及写法,或者点击链接到github查看源代码。
@Test
void shouldPassAllParametersToPostForRegistrationOfNonElasticAgent() throws IOException {
String url = "http://cruise.com/go";
GoAgentServerHttpClient httpClient = mock(GoAgentServerHttpClient.class);
final CloseableHttpResponse response = mock(CloseableHttpResponse.class);
final ProtocolVersion protocolVersion = new ProtocolVersion("https", 1, 2);
when(response.getStatusLine()).thenReturn(new BasicStatusLine(protocolVersion, HttpStatus.OK.value(), null));
when(response.getEntity()).thenReturn(new StringEntity(""));
when(httpClient.execute(isA(HttpRequestBase.class))).thenReturn(response);
final DefaultAgentRegistry defaultAgentRegistry = new DefaultAgentRegistry();
Properties properties = new Properties();
properties.put(AgentAutoRegistrationPropertiesImpl.AGENT_AUTO_REGISTER_KEY, "t0ps3cret");
properties.put(AgentAutoRegistrationPropertiesImpl.AGENT_AUTO_REGISTER_RESOURCES, "linux, java");
properties.put(AgentAutoRegistrationPropertiesImpl.AGENT_AUTO_REGISTER_ENVIRONMENTS, "uat, staging");
properties.put(AgentAutoRegistrationPropertiesImpl.AGENT_AUTO_REGISTER_HOSTNAME, "agent01.example.com");
remoteRegistryRequester(url, httpClient, defaultAgentRegistry, 200).requestRegistration("cruise.com", new AgentAutoRegistrationPropertiesImpl(null, properties));
verify(httpClient).execute(argThat(hasAllParams(defaultAgentRegistry.uuid(), "", "")));
}
private String generateViaHeader(HttpMessage msg) {
final VersionInfo vi = VersionInfo.loadVersionInfo(
"org.apache.http.client", getClass().getClassLoader());
final String release = (vi != null) ? vi.getRelease()
: VersionInfo.UNAVAILABLE;
final ProtocolVersion pv = msg.getProtocolVersion();
if ("http".equalsIgnoreCase(pv.getProtocol())) {
return String.format(
"%d.%d localhost (Apache-HttpClient/%s (cache))",
pv.getMajor(), pv.getMinor(), release);
} else {
return String.format(
"%s/%d.%d localhost (Apache-HttpClient/%s (cache))",
pv.getProtocol(), pv.getMajor(), pv.getMinor(), release);
}
}
/**
* Ctor.
*
* @param status The {@link HttpStatus http status code}
* @param jsonPayload The json payload
*/
public Response(final int status, final String jsonPayload) {
this.backbone = new BasicHttpResponse(
new BasicStatusLine(
new ProtocolVersion("HTTP", 1, 1), status, "REASON"
)
);
this.backbone.setEntity(
new StringEntity(
jsonPayload, ContentType.APPLICATION_JSON
)
);
this.backbone.setHeader("Date", new Date().toString());
this.backbone.setHeader(
"Content-Length", String.valueOf(jsonPayload.getBytes().length)
);
this.backbone.setHeader("Content-Type", "application/json");
}
@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));
}
/**
* 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)
);
}
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 testMap() {
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());
}
private Response fetchResponse(HttpURLConnection connection) throws IOException {
// Initialize HttpResponse with data from the HttpURLConnection.
ProtocolVersion protocolVersion = new ProtocolVersion("HTTP", 1, 1);
int responseCode = connection.getResponseCode();
if (responseCode == -1) {
throw new IOException("Could not retrieve response code from HttpUrlConnection.");
}
// 状态行数据
StatusLine responseStatus = new BasicStatusLine(protocolVersion,
connection.getResponseCode(), connection.getResponseMessage());
// 构建response
Response response = new Response(responseStatus);
// 设置response数据
response.setEntity(entityFromURLConnwction(connection));
addHeadersToResponse(response, connection);
return response;
}
@Override
public HttpResponse build() {
ProtocolVersion protocolVersion = new ProtocolVersion("HTTP", 1, 1);
StatusLine statusLine = new BasicStatusLine(protocolVersion, status, "");
HttpResponse response = new BasicHttpResponse(statusLine);
InputStream is = new ByteArrayInputStream(body.getBytes(StandardCharsets.UTF_8));
BasicHttpEntity entity = new BasicHttpEntity();
entity.setContent(is);
response.setEntity(entity);
for (Map.Entry<String, List<String>> header : headers.entrySet()) {
for (String value : header.getValue()) {
response.addHeader(header.getKey(), value);
}
}
return response;
}
private org.apache.http.HttpResponse convertResponseNewToOld(HttpResponse resp)
throws IllegalStateException, IOException {
ProtocolVersion protocolVersion = new ProtocolVersion(resp.getProtocolVersion()
.getProtocol(),
resp.getProtocolVersion().getMajor(),
resp.getProtocolVersion().getMinor());
StatusLine responseStatus = new BasicStatusLine(protocolVersion,
resp.getStatusLine().getStatusCode(),
resp.getStatusLine().getReasonPhrase());
BasicHttpResponse response = new BasicHttpResponse(responseStatus);
org.apache.http.HttpEntity ent = convertEntityNewToOld(resp.getEntity());
response.setEntity(ent);
for (Header h : resp.getAllHeaders()) {
org.apache.http.Header header = convertheaderNewToOld(h);
response.addHeader(header);
}
return response;
}
@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);
}
}
public void testHeadersPreservedWhenError500() 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("Dummy", "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);
assertTrue("Header 'Dummy'", driverResponse.containsHeader("Dummy"));
}
/**
* 0000162: Cookie forwarding (Browser->Server) does not work with preserveHost
* <p>
* This test is to ensure behavior with preserve host off (already working as of bug 162).
*
* @throws Exception
* @see <a href="http://www.esigate.org/mantisbt/view.php?id=162">0000162</a>
*/
public void testBug162PreserveHostOff() throws Exception {
Properties properties = new Properties();
properties.put(Parameters.REMOTE_URL_BASE.getName(), "http://localhost.mydomain.fr/");
properties.put(Parameters.PRESERVE_HOST.getName(), "false");
mockConnectionManager = new MockConnectionManager() {
@Override
public HttpResponse execute(HttpRequest httpRequest) {
Assert.assertEquals("localhost.mydomain.fr", httpRequest.getFirstHeader("Host").getValue());
Assert.assertTrue("Cookie must be forwarded", httpRequest.containsHeader("Cookie"));
return new BasicHttpResponse(new ProtocolVersion("HTTP", 1, 1), HttpStatus.SC_OK, "OK");
}
};
Driver driver = createMockDriver(properties, mockConnectionManager);
request =
TestUtils.createIncomingRequest("http://test.mydomain.fr/foobar/").addCookie(
new BasicClientCookie("TEST_cookie", "233445436436346"));
driver.proxy("/foobar/", request.build());
}
@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);
}
}
/**
* Sets up tests by creating a unique instance of the tested class, and by defining the behaviour of the mocked
* classes.
*
* @throws Exception
*/
@Before
public void setUp() throws Exception {
// set up the instance of the tested class
backend = new HDFSBackendImplREST(hdfsHost, hdfsPort, user, password, token, hiveServerVersion, hiveHost,
hivePort, false, null, null, null, null, false, maxConns, maxConnsPerRoute);
// set up other instances
BasicHttpResponse resp200 = new BasicHttpResponse(new ProtocolVersion("HTTP", 1, 1), 200, "OK");
resp200.addHeader("Content-Type", "application/json");
BasicHttpResponse resp201 = new BasicHttpResponse(new ProtocolVersion("HTTP", 1, 1), 201, "Created");
resp201.addHeader("Content-Type", "application/json");
BasicHttpResponse resp307 = new BasicHttpResponse(new ProtocolVersion("HTTP", 1, 1), 307, "Temporary Redirect");
resp307.addHeader("Content-Type", "application/json");
resp307.addHeader(new BasicHeader("Location", "http://localhost:14000/"));
// set up the behaviour of the mocked classes
when(mockHttpClientExistsCreateDir.execute(Mockito.any(HttpUriRequest.class))).thenReturn(resp200);
when(mockHttpClientCreateFile.execute(Mockito.any(HttpUriRequest.class))).thenReturn(resp307, resp201);
when(mockHttpClientAppend.execute(Mockito.any(HttpUriRequest.class))).thenReturn(resp307, resp200);
}
@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 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 sendInOnlyNoResponse() throws Exception {
CamelContext camelctx = createCamelContext();
MockEndpoint result = camelctx.getEndpoint("mock:result", MockEndpoint.class);
result.expectedMessageCount(0);
camelctx.start();
try {
ProducerTemplate template = camelctx.createProducerTemplate();
HttpEntity mockHttpEntity = mock(HttpEntity.class);
when(mockHttpEntity.getContent()).thenReturn(null);
when(closeableHttpResponse.getEntity()).thenReturn(mockHttpEntity);
when(closeableHttpResponse.getStatusLine())
.thenReturn(new BasicStatusLine(new ProtocolVersion("HTTP", 1, 1), 200, ""));
result.assertIsSatisfied();
} finally {
camelctx.close();
}
}
@Test
public void httpClientGetsClosed() throws IOException, AuthenticationException {
CloseableHttpClient httpClient = Mockito.mock( CloseableHttpClient.class );
CloseableHttpResponse response = Mockito.mock( CloseableHttpResponse.class );
HTTPProtocol httpProtocol = new HTTPProtocol() {
@Override CloseableHttpClient openHttpClient( String username, String password ) {
return httpClient;
}
};
String urlAsString = "http://url/path";
when( httpClient.execute( Matchers.argThat( matchesGet() ) ) ).thenReturn( response );
StatusLine statusLine = new BasicStatusLine( new ProtocolVersion( "http", 2, 0 ), HttpStatus.SC_OK, "blah" );
BasicHttpEntity entity = new BasicHttpEntity();
String content = "plenty of mocks for this test";
entity.setContent( new ByteArrayInputStream( content.getBytes() ) );
when( response.getEntity() ).thenReturn( entity );
when( response.getStatusLine() ).thenReturn( statusLine );
assertEquals( content, httpProtocol.get( urlAsString, "", "" ) );
verify( httpClient ).close();
}
@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
void shouldPassAllParametersToPostForRegistrationOfElasticAgent() throws IOException {
String url = "http://cruise.com/go";
GoAgentServerHttpClient httpClient = mock(GoAgentServerHttpClient.class);
final CloseableHttpResponse response = mock(CloseableHttpResponse.class);
final ProtocolVersion protocolVersion = new ProtocolVersion("https", 1, 2);
when(response.getStatusLine()).thenReturn(new BasicStatusLine(protocolVersion, HttpStatus.OK.value(), null));
when(response.getEntity()).thenReturn(new StringEntity(""));
when(httpClient.execute(isA(HttpRequestBase.class))).thenReturn(response);
final DefaultAgentRegistry defaultAgentRegistry = new DefaultAgentRegistry();
Properties properties = new Properties();
properties.put(AgentAutoRegistrationPropertiesImpl.AGENT_AUTO_REGISTER_KEY, "t0ps3cret");
properties.put(AgentAutoRegistrationPropertiesImpl.AGENT_AUTO_REGISTER_RESOURCES, "linux, java");
properties.put(AgentAutoRegistrationPropertiesImpl.AGENT_AUTO_REGISTER_ENVIRONMENTS, "uat, staging");
properties.put(AgentAutoRegistrationPropertiesImpl.AGENT_AUTO_REGISTER_HOSTNAME, "agent01.example.com");
properties.put(AgentAutoRegistrationPropertiesImpl.AGENT_AUTO_REGISTER_ELASTIC_AGENT_ID, "42");
properties.put(AgentAutoRegistrationPropertiesImpl.AGENT_AUTO_REGISTER_ELASTIC_PLUGIN_ID, "tw.go.elastic-agent.docker");
remoteRegistryRequester(url, httpClient, defaultAgentRegistry, 200).requestRegistration("cruise.com", new AgentAutoRegistrationPropertiesImpl(null, properties));
verify(httpClient).execute(argThat(hasAllParams(defaultAgentRegistry.uuid(), "42", "tw.go.elastic-agent.docker")));
}
/**
* Test that we don't have a NullpointerException when forcing the caching (ttl).
*
* @throws Exception
*/
public void testForcedTtlWith302ResponseCode() throws Exception {
properties = new PropertiesBuilder() //
.set(Parameters.REMOTE_URL_BASE, "http://localhost:8080") //
.set(Parameters.TTL, 1000) //
.build();
createHttpClientRequestExecutor();
DriverRequest originalRequest = TestUtils.createDriverRequest(driver);
OutgoingRequest request =
httpClientRequestExecutor.createOutgoingRequest(originalRequest, "http://localhost:8080", true);
HttpResponse response =
new BasicHttpResponse(new BasicStatusLine(new ProtocolVersion("HTTP", 1, 1),
HttpStatus.SC_MOVED_TEMPORARILY, "Moved temporarily"));
response.addHeader("Location", "http://www.foo.com");
mockConnectionManager.setResponse(response);
HttpResponse result = httpClientRequestExecutor.execute(request);
if (result.getEntity() != null) {
result.getEntity().writeTo(new NullOutputStream());
// We should have had a NullpointerException
}
}
@Test
public void happyPathWorks() throws ClientProtocolException, IOException {
String responseBodyStr = "{"
+ "\"access_token\": \"new access token\","
+ "\"token_type\": \"bearer\","
+ "\"refresh_token\": \"new refresh token\","
+ "\"expires_in\": 86399,"
+ "\"scope\": \"x:devices:* i:deviceprofiles r:devices:* w:devices:*\","
+ "\"installed_app_id\": \"installed app id\""
+ "}";
InputStream responseBodyStream =
new ByteArrayInputStream(responseBodyStr.getBytes(StandardCharsets.UTF_8));
when(httpClient.execute(any())).thenReturn(response);
when(response.getStatusLine())
.thenReturn(new BasicStatusLine(new ProtocolVersion("HTTP", 1, 1), 200, null));
when(response.getEntity()).thenReturn(entity);
when(entity.getContent()).thenReturn(responseBodyStream);
Token expected = new Token()
.accessToken("new access token")
.accessTokenExpiration(now.plusSeconds(86399))
.refreshToken("new refresh token")
.refreshTokenExpiration(now.plus(Duration.ofDays(30)));
Token result = tester.refresh(token);
assertEquals(result, expected);
ArgumentCaptor<HttpUriRequest> requestCaptor =
ArgumentCaptor.forClass(HttpUriRequest.class);
verify(httpClient).execute(requestCaptor.capture());
HttpUriRequest capturedRequest = requestCaptor.getValue();
assertEquals("http://example.com/tokenRefreshUrl",
capturedRequest.getURI().toString());
}
HeaderResponseHandler(ResponseHandler<T> responseHandler, Map<String, List<Header>> headers, Locale locale,
ProtocolVersion protocolVersion, StatusLine statusLine) {
this.responseHandler = Objects.requireNonNull(responseHandler);
this.headers = headers;
this.locale = locale;
this.protocolVersion = protocolVersion;
this.statusLine = statusLine;
}
public OutgoingRequest(String method, String uri, ProtocolVersion version, DriverRequest originalRequest,
RequestConfig requestConfig, OutgoingRequestContext context) {
super(method, uri, version);
requestLine = new BasicRequestLine(method, uri, version);
this.requestConfig = requestConfig;
this.context = context;
this.originalRequest = originalRequest;
}
/**
* @deprecated use {@link #executeRequest} instead to avoid a dependency on the deprecated
* Apache HTTP library. Nothing in Volley's own source calls this method. However, since
* {@link BasicNetwork#mHttpStack} is exposed to subclasses, we provide this implementation
* in case legacy client apps are dependent on that field. This method may be removed in a
* future release of Volley.
*/
@Deprecated
@Override
public final org.apache.http.HttpResponse performRequest(
Request<?> request, Map<String, String> additionalHeaders)
throws IOException, AuthFailureError {
HttpResponse response = executeRequest(request, additionalHeaders);
ProtocolVersion protocolVersion = new ProtocolVersion("HTTP", 1, 1);
StatusLine statusLine =
new BasicStatusLine(
protocolVersion, response.getStatusCode(), /* reasonPhrase= */ "");
BasicHttpResponse apacheResponse = new BasicHttpResponse(statusLine);
List<org.apache.http.Header> headers = new ArrayList<>();
for (Header header : response.getHeaders()) {
headers.add(new BasicHeader(header.getName(), header.getValue()));
}
apacheResponse.setHeaders(headers.toArray(new org.apache.http.Header[0]));
InputStream responseStream = response.getContent();
if (responseStream != null) {
BasicHttpEntity entity = new BasicHttpEntity();
entity.setContent(responseStream);
entity.setContentLength(response.getContentLength());
apacheResponse.setEntity(entity);
}
return apacheResponse;
}
@Test
public void testLoginFailure() {
final GenericException f = new GenericException(
"message", new Header[]{}, new BasicStatusLine(new ProtocolVersion("http", 1, 1), 403, "Forbidden"));
assertTrue(new SwiftExceptionMappingService().map(f) instanceof AccessDeniedException);
assertEquals("Access denied", new SwiftExceptionMappingService().map(f).getMessage());
assertEquals("Message. 403 Forbidden. Please contact your web hosting service provider for assistance.", new SwiftExceptionMappingService().map(f).getDetail());
}
private static HttpResponseProxy createHttpResponseProxy(HttpEntity entity) {
ProtocolVersion protocolVersion = new ProtocolVersion("HTTP", 1, 1);
BasicStatusLine statusLine = new BasicStatusLine(protocolVersion, 200, "mock response");
BasicHttpResponse response = new BasicHttpResponse(statusLine);
response.setEntity(entity);
return new HttpResponseProxy(response);
}