本文整理匯總了Java中org.apache.http.message.BasicHttpResponse類的典型用法代碼示例。如果您正苦於以下問題:Java BasicHttpResponse類的具體用法?Java BasicHttpResponse怎麽用?Java BasicHttpResponse使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。
BasicHttpResponse類屬於org.apache.http.message包,在下文中一共展示了BasicHttpResponse類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。
示例1: testOAuthStepTwo
import org.apache.http.message.BasicHttpResponse; //導入依賴的package包/類
@Test
public void testOAuthStepTwo() throws IOException {
//Create the mock response
HttpResponse postResponse = new BasicHttpResponse(new ProtocolVersion("TEST", 0, 0), 200, "TEST");
postResponse.setEntity(new StringEntity(oauthStepTwoTestJSON));
//Set the call providers mock response
callProvider.setPostResponse(postResponse);
//Perform mock oauth step 2
Credentials credentials = client.oauthStepTwo(null, null);
//Check null is not returned
assertNotNull(credentials);
//Check the info is what it should be
assertEquals("access_token", credentials.getAccessToken());
assertEquals("refresh_token", credentials.getRefreshToken());
assertEquals("1234567890", credentials.getDateGenerated());
}
示例2: testPerformRequestOnResponseExceptionWithBrokenEntity2
import org.apache.http.message.BasicHttpResponse; //導入依賴的package包/類
public void testPerformRequestOnResponseExceptionWithBrokenEntity2() throws IOException {
MainRequest mainRequest = new MainRequest();
CheckedFunction<MainRequest, Request, IOException> requestConverter = request ->
new Request("GET", "/", Collections.emptyMap(), null);
RestStatus restStatus = randomFrom(RestStatus.values());
HttpResponse httpResponse = new BasicHttpResponse(newStatusLine(restStatus));
httpResponse.setEntity(new StringEntity("{\"status\":" + restStatus.getStatus() + "}", ContentType.APPLICATION_JSON));
Response mockResponse = new Response(REQUEST_LINE, new HttpHost("localhost", 9200), httpResponse);
ResponseException responseException = new ResponseException(mockResponse);
when(restClient.performRequest(anyString(), anyString(), anyMapOf(String.class, String.class),
anyObject(), anyVararg())).thenThrow(responseException);
ElasticsearchException elasticsearchException = expectThrows(ElasticsearchException.class,
() -> restHighLevelClient.performRequest(mainRequest, requestConverter,
response -> response.getStatusLine().getStatusCode(), Collections.emptySet()));
assertEquals("Unable to parse response body", elasticsearchException.getMessage());
assertEquals(restStatus, elasticsearchException.status());
assertSame(responseException, elasticsearchException.getCause());
assertThat(elasticsearchException.getSuppressed()[0], instanceOf(IllegalStateException.class));
}
示例3: post_whenResponseIsFailure_logsException
import org.apache.http.message.BasicHttpResponse; //導入依賴的package包/類
@Test
public void post_whenResponseIsFailure_logsException() throws IOException {
ArgumentCaptor<HttpPost> requestCaptor = ArgumentCaptor.forClass(HttpPost.class);
HttpClient httpClient = mock(HttpClient.class);
BasicHttpResponse response = new BasicHttpResponse(new BasicStatusLine(new ProtocolVersion("http", 1, 1), 400, ""));
response.setEntity(new StringEntity("failure reason here"));
when(httpClient.execute(requestCaptor.capture())).thenReturn(response);
MsTeamsNotification w = factory.getMsTeamsNotification(httpClient);
MsTeamsNotificationPayloadContent content = new MsTeamsNotificationPayloadContent();
content.setBuildDescriptionWithLinkSyntax("http://foo");
content.setCommits(new ArrayList<Commit>());
w.setPayload(content);
w.setEnabled(true);
w.post();
assertNotNull(w.getResponse());
assertFalse(w.getResponse().getOk());
}
示例4: createOkSearchResponse
import org.apache.http.message.BasicHttpResponse; //導入依賴的package包/類
private BasicHttpResponse createOkSearchResponse() throws UnsupportedEncodingException {
BasicHttpResponse okSearchResponse = createOkResponse();
HttpEntity searchResponseEntity = new StringEntity("" +
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
" <D:multistatus xmlns:D=\"DAV:\"\n" +
" xmlns:R=\"http://example.org/propschema\">\n" +
" <D:response>" +
" <D:propstat>\n" +
" <uid>Inbox</uid>" +
" <href>http://example.org/Exchange/user/Inbox</href>\n" +
" </D:propstat></D:response>\n" +
" <D:response>" +
" <D:propstat>\n" +
" <uid>Drafts</uid>" +
" <href>http://example.org/Exchange/user/Drafts</href>\n" +
" </D:propstat></D:response>\n" +
" <D:response>" +
" <D:propstat>\n" +
" <uid>Folder2</uid>" +
" <href>http://example.org/Exchange/user/Folder2</href>\n" +
" </D:propstat></D:response>\n" +
" </D:multistatus>");
okSearchResponse.setEntity(searchResponseEntity);
return okSearchResponse;
}
示例5: transformResponse
import org.apache.http.message.BasicHttpResponse; //導入依賴的package包/類
private static HttpResponse transformResponse(Response response) {
int code = response.code();
String message = response.message();
BasicHttpResponse httpResponse = new BasicHttpResponse(HTTP_1_1, code, message);
ResponseBody body = response.body();
InputStreamEntity entity = new InputStreamEntity(body.byteStream(), body.contentLength());
httpResponse.setEntity(entity);
Headers headers = response.headers();
for (int i = 0, size = headers.size(); i < size; i++) {
String name = headers.name(i);
String value = headers.value(i);
httpResponse.addHeader(name, value);
if ("Content-Type".equalsIgnoreCase(name)) {
entity.setContentType(value);
} else if ("Content-Encoding".equalsIgnoreCase(name)) {
entity.setContentEncoding(value);
}
}
return httpResponse;
}
示例6: checkRefreshToken
import org.apache.http.message.BasicHttpResponse; //導入依賴的package包/類
/**
* Checks to make sure that tokens and dates are refreshed given a valid response from google
* Gives a mock response from google with "new" access code
* @throws IOException
*/
@Test
public void checkRefreshToken() throws IOException {
long dateGenerated = Instant.now().getEpochSecond() - (3600*2);
credentials = new Credentials(jsonWithoutDate, dateGenerated);
//Create mock response
MockCall callProvider = new MockCall();
HttpResponse postResponse = new BasicHttpResponse(new ProtocolVersion("TEST", 0, 0), 200, "TEST");
postResponse.setEntity(new StringEntity("{ \"access_token\":\"new_access_token\", \"expires_in\":3920, \"token_type\":\"Bearer\" }"));
callProvider.setPostResponse(postResponse);
//Make assertions
assertTrue(credentials.refreshToken(null, null, callProvider));
assertEquals("new_access_token", credentials.getAccessToken());
assertNotEquals(String.valueOf(dateGenerated), credentials.getDateGenerated());
}
示例7: testPerformRequestOnSuccess
import org.apache.http.message.BasicHttpResponse; //導入依賴的package包/類
public void testPerformRequestOnSuccess() throws IOException {
MainRequest mainRequest = new MainRequest();
CheckedFunction<MainRequest, Request, IOException> requestConverter = request ->
new Request("GET", "/", Collections.emptyMap(), null);
RestStatus restStatus = randomFrom(RestStatus.values());
HttpResponse httpResponse = new BasicHttpResponse(newStatusLine(restStatus));
Response mockResponse = new Response(REQUEST_LINE, new HttpHost("localhost", 9200), httpResponse);
when(restClient.performRequest(anyString(), anyString(), anyMapOf(String.class, String.class),
anyObject(), anyVararg())).thenReturn(mockResponse);
{
Integer result = restHighLevelClient.performRequest(mainRequest, requestConverter,
response -> response.getStatusLine().getStatusCode(), Collections.emptySet());
assertEquals(restStatus.getStatus(), result.intValue());
}
{
IOException ioe = expectThrows(IOException.class, () -> restHighLevelClient.performRequest(mainRequest,
requestConverter, response -> {throw new IllegalStateException();}, Collections.emptySet()));
assertEquals("Unable to parse response body for Response{requestLine=GET / http/1.1, host=http://localhost:9200, " +
"response=http/1.1 " + restStatus.getStatus() + " " + restStatus.name() + "}", ioe.getMessage());
}
}
示例8: testPerformRequestOnResponseExceptionWithoutEntity
import org.apache.http.message.BasicHttpResponse; //導入依賴的package包/類
public void testPerformRequestOnResponseExceptionWithoutEntity() throws IOException {
MainRequest mainRequest = new MainRequest();
CheckedFunction<MainRequest, Request, IOException> requestConverter = request ->
new Request("GET", "/", Collections.emptyMap(), null);
RestStatus restStatus = randomFrom(RestStatus.values());
HttpResponse httpResponse = new BasicHttpResponse(newStatusLine(restStatus));
Response mockResponse = new Response(REQUEST_LINE, new HttpHost("localhost", 9200), httpResponse);
ResponseException responseException = new ResponseException(mockResponse);
when(restClient.performRequest(anyString(), anyString(), anyMapOf(String.class, String.class),
anyObject(), anyVararg())).thenThrow(responseException);
ElasticsearchException elasticsearchException = expectThrows(ElasticsearchException.class,
() -> restHighLevelClient.performRequest(mainRequest, requestConverter,
response -> response.getStatusLine().getStatusCode(), Collections.emptySet()));
assertEquals(responseException.getMessage(), elasticsearchException.getMessage());
assertEquals(restStatus, elasticsearchException.status());
assertSame(responseException, elasticsearchException.getCause());
}
示例9: testPerformRequestOnResponseExceptionWithIgnoresErrorNoBody
import org.apache.http.message.BasicHttpResponse; //導入依賴的package包/類
public void testPerformRequestOnResponseExceptionWithIgnoresErrorNoBody() throws IOException {
MainRequest mainRequest = new MainRequest();
CheckedFunction<MainRequest, Request, IOException> requestConverter = request ->
new Request("GET", "/", Collections.emptyMap(), null);
HttpResponse httpResponse = new BasicHttpResponse(newStatusLine(RestStatus.NOT_FOUND));
Response mockResponse = new Response(REQUEST_LINE, new HttpHost("localhost", 9200), httpResponse);
ResponseException responseException = new ResponseException(mockResponse);
when(restClient.performRequest(anyString(), anyString(), anyMapOf(String.class, String.class),
anyObject(), anyVararg())).thenThrow(responseException);
ElasticsearchException elasticsearchException = expectThrows(ElasticsearchException.class,
() -> restHighLevelClient.performRequest(mainRequest, requestConverter,
response -> {throw new IllegalStateException();}, Collections.singleton(404)));
assertEquals(RestStatus.NOT_FOUND, elasticsearchException.status());
assertSame(responseException, elasticsearchException.getCause());
assertEquals(responseException.getMessage(), elasticsearchException.getMessage());
}
示例10: testPerformRequestOnResponseExceptionWithIgnoresErrorValidBody
import org.apache.http.message.BasicHttpResponse; //導入依賴的package包/類
public void testPerformRequestOnResponseExceptionWithIgnoresErrorValidBody() throws IOException {
MainRequest mainRequest = new MainRequest();
CheckedFunction<MainRequest, Request, IOException> requestConverter = request ->
new Request("GET", "/", Collections.emptyMap(), null);
HttpResponse httpResponse = new BasicHttpResponse(newStatusLine(RestStatus.NOT_FOUND));
httpResponse.setEntity(new StringEntity("{\"error\":\"test error message\",\"status\":404}",
ContentType.APPLICATION_JSON));
Response mockResponse = new Response(REQUEST_LINE, new HttpHost("localhost", 9200), httpResponse);
ResponseException responseException = new ResponseException(mockResponse);
when(restClient.performRequest(anyString(), anyString(), anyMapOf(String.class, String.class),
anyObject(), anyVararg())).thenThrow(responseException);
ElasticsearchException elasticsearchException = expectThrows(ElasticsearchException.class,
() -> restHighLevelClient.performRequest(mainRequest, requestConverter,
response -> {throw new IllegalStateException();}, Collections.singleton(404)));
assertEquals(RestStatus.NOT_FOUND, elasticsearchException.status());
assertSame(responseException, elasticsearchException.getSuppressed()[0]);
assertEquals("Elasticsearch exception [type=exception, reason=test error message]", elasticsearchException.getMessage());
}
示例11: bufferLimitTest
import org.apache.http.message.BasicHttpResponse; //導入依賴的package包/類
private static void bufferLimitTest(HeapBufferedAsyncResponseConsumer consumer, int bufferLimit) throws Exception {
ProtocolVersion protocolVersion = new ProtocolVersion("HTTP", 1, 1);
StatusLine statusLine = new BasicStatusLine(protocolVersion, 200, "OK");
consumer.onResponseReceived(new BasicHttpResponse(statusLine));
final AtomicReference<Long> contentLength = new AtomicReference<>();
HttpEntity entity = new StringEntity("", ContentType.APPLICATION_JSON) {
@Override
public long getContentLength() {
return contentLength.get();
}
};
contentLength.set(randomLong(bufferLimit));
consumer.onEntityEnclosed(entity, ContentType.APPLICATION_JSON);
contentLength.set(randomLongBetween(bufferLimit + 1, MAX_TEST_BUFFER_SIZE));
try {
consumer.onEntityEnclosed(entity, ContentType.APPLICATION_JSON);
} catch(ContentTooLongException e) {
assertEquals("entity content is too long [" + entity.getContentLength() +
"] for the configured buffer limit [" + bufferLimit + "]", e.getMessage());
}
}
示例12: testExecute_non2xx_exception
import org.apache.http.message.BasicHttpResponse; //導入依賴的package包/類
@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());
}
}
示例13: segmentInResponseToCode
import org.apache.http.message.BasicHttpResponse; //導入依賴的package包/類
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;
}
示例14: logsRequestAndResponseFields
import org.apache.http.message.BasicHttpResponse; //導入依賴的package包/類
@Test
public void logsRequestAndResponseFields() {
HttpContext context = new BasicHttpContext();
context.setAttribute(HTTP_TARGET_HOST, "http://www.google.com");
OutboundRequestLoggingInterceptor interceptor = new OutboundRequestLoggingInterceptor(new FakeClock(20));
interceptor.process(new BasicHttpRequest("GET", "/something"), context);
interceptor.process(new BasicHttpResponse(new BasicStatusLine(ANY_PROTOCOL, 200, "any")), context);
Map<String, Object> fields = new ConcurrentHashMap<>();
fields.put("requestMethod", "GET");
fields.put("requestURI", "http://www.google.com/something");
testAppender.assertEvent(0, INFO, "Outbound request start", appendEntries(fields));
fields.put("responseTime", 20L);
fields.put("responseCode", 200);
testAppender.assertEvent(1, INFO, "Outbound request finish", appendEntries(fields));
}
示例15: allowEmptyConstructorToBuildDefaultClock
import org.apache.http.message.BasicHttpResponse; //導入依賴的package包/類
@Test
public void allowEmptyConstructorToBuildDefaultClock() {
testAppender.clearEvents();
HttpContext context = new BasicHttpContext();
context.setAttribute(HTTP_TARGET_HOST, "http://www.google.com");
OutboundRequestLoggingInterceptor interceptor = new OutboundRequestLoggingInterceptor();
interceptor.process(new BasicHttpRequest("GET", "/something"), context);
interceptor.process(new BasicHttpResponse(new BasicStatusLine(ANY_PROTOCOL, 200, "any")), context);
assertThat(testAppender.getEvents()).extracting("message")
.contains("Outbound request start", Index.atIndex(0))
.contains("Outbound request finish", Index.atIndex(1));
}