本文整理汇总了Java中org.apache.http.HttpVersion.HTTP_1_1属性的典型用法代码示例。如果您正苦于以下问题:Java HttpVersion.HTTP_1_1属性的具体用法?Java HttpVersion.HTTP_1_1怎么用?Java HttpVersion.HTTP_1_1使用的例子?那么恭喜您, 这里精选的属性代码示例或许可以为您提供帮助。您也可以进一步了解该属性所在类org.apache.http.HttpVersion
的用法示例。
在下文中一共展示了HttpVersion.HTTP_1_1属性的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: testExecute_non2xx_exception
@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());
}
}
示例2: segmentInResponseToCode
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;
}
示例3: toProtocolVersion
private ProtocolVersion toProtocolVersion(String httpVersion) {
switch (httpVersion) {
case "HTTP/0.9":
case "0.9":
return HttpVersion.HTTP_0_9;
case "HTTP/1.0":
case "1.0":
return HttpVersion.HTTP_1_0;
case "HTTP/1.1":
case "1.1":
return HttpVersion.HTTP_1_1;
default:
throw new IllegalArgumentException("Invalid HTTP version: " + httpVersion);
}
}
示例4: waitForServerReady
/**
* Wait for the server is ready.
*/
private void waitForServerReady() throws IOException, InterruptedException {
final HttpGet httpget = new HttpGet(getPingUri());
HttpResponse response = new BasicHttpResponse(new BasicStatusLine(HttpVersion.HTTP_1_1, HttpStatus.SC_NOT_FOUND, ""));
int counter = 0;
while (true) {
try {
response = httpclient.execute(httpget);
final int status = response.getStatusLine().getStatusCode();
if (status == HttpStatus.SC_OK) {
break;
}
checkRetries(counter);
} catch (final HttpHostConnectException ex) { // NOSONAR - Wait, and check later
log.info("Check failed, retrying...");
checkRetries(counter);
} finally {
EntityUtils.consume(response.getEntity());
}
counter++;
}
}
示例5: consumesBodyOf100ContinueResponseIfItArrives
@Test
public void consumesBodyOf100ContinueResponseIfItArrives() throws Exception {
final HttpEntityEnclosingRequest req = new BasicHttpEntityEnclosingRequest("POST", "/", HttpVersion.HTTP_1_1);
final int nbytes = 128;
req.setHeader("Content-Length","" + nbytes);
req.setHeader("Content-Type", "application/octet-stream");
final HttpEntity postBody = new ByteArrayEntity(HttpTestUtils.getRandomBytes(nbytes));
req.setEntity(postBody);
final HttpRequestWrapper wrapper = HttpRequestWrapper.wrap(req);
final HttpResponse resp = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_CONTINUE, "Continue");
final Flag closed = new Flag();
final ByteArrayInputStream bais = makeTrackableBody(nbytes, closed);
resp.setEntity(new InputStreamEntity(bais, -1));
try {
impl.ensureProtocolCompliance(wrapper, resp);
} catch (final ClientProtocolException expected) {
}
assertTrue(closed.set || bais.read() == -1);
}
示例6: testAuthenticationException
@Test
public void testAuthenticationException() throws Exception {
final HttpHost host = new HttpHost("somehost", 80);
final HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_UNAUTHORIZED, "UNAUTHORIZED");
this.authState.setState(AuthProtocolState.CHALLENGED);
Mockito.doThrow(new MalformedChallengeException()).when(this.defltAuthStrategy).getChallenges(
Mockito.any(HttpHost.class),
Mockito.any(HttpResponse.class),
Mockito.any(HttpContext.class));
Assert.assertFalse(this.httpAuthenticator.handleAuthChallenge(host,
response, this.defltAuthStrategy, this.authState, this.context));
Assert.assertEquals(AuthProtocolState.UNCHALLENGED, this.authState.getState());
Assert.assertNull(this.authState.getAuthScheme());
Assert.assertNull(this.authState.getCredentials());
}
示例7: testNoCookieSpec
@Test
public void testNoCookieSpec() throws Exception {
final HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, 200, "OK");
response.addHeader(SM.SET_COOKIE, "name1=value1");
final HttpClientContext context = HttpClientContext.create();
context.setAttribute(HttpClientContext.COOKIE_ORIGIN, this.cookieOrigin);
context.setAttribute(HttpClientContext.COOKIE_SPEC, null);
context.setAttribute(HttpClientContext.COOKIE_STORE, this.cookieStore);
final HttpResponseInterceptor interceptor = new ResponseProcessCookies();
interceptor.process(response, context);
final List<Cookie> cookies = this.cookieStore.getCookies();
Assert.assertNotNull(cookies);
Assert.assertEquals(0, cookies.size());
}
示例8: testUnsuccessfulResponse
@SuppressWarnings("boxing")
@Test
public void testUnsuccessfulResponse() throws Exception {
final InputStream instream = Mockito.mock(InputStream.class);
final HttpEntity entity = Mockito.mock(HttpEntity.class);
Mockito.when(entity.isStreaming()).thenReturn(true);
Mockito.when(entity.getContent()).thenReturn(instream);
final StatusLine sl = new BasicStatusLine(HttpVersion.HTTP_1_1, 404, "Not Found");
final HttpResponse response = Mockito.mock(HttpResponse.class);
Mockito.when(response.getStatusLine()).thenReturn(sl);
Mockito.when(response.getEntity()).thenReturn(entity);
final BasicResponseHandler handler = new BasicResponseHandler();
try {
handler.handleResponse(response);
Assert.fail("HttpResponseException expected");
} catch (final HttpResponseException ex) {
Assert.assertEquals(404, ex.getStatusCode());
Assert.assertEquals("Not Found", ex.getMessage());
}
Mockito.verify(entity).getContent();
Mockito.verify(instream).close();
}
示例9: setUp
@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();
}
示例10: testLambdaInvokeSubsegmentContainsFunctionName
@Test
public void testLambdaInvokeSubsegmentContainsFunctionName() {
// Setup test
AWSLambda lambda = AWSLambdaClientBuilder.standard().withRequestHandlers(new TracingHandler()).withRegion(Regions.US_EAST_1).withCredentials(new AWSStaticCredentialsProvider(new BasicAWSCredentials("fake", "fake"))).build();
AmazonHttpClient amazonHttpClient = new AmazonHttpClient(new ClientConfiguration());
ConnectionManagerAwareHttpClient apacheHttpClient = Mockito.mock(ConnectionManagerAwareHttpClient.class);
HttpResponse httpResponse = new BasicHttpResponse(new BasicStatusLine(HttpVersion.HTTP_1_1, 200, "OK"));
BasicHttpEntity responseBody = new BasicHttpEntity();
responseBody.setContent(new ByteArrayInputStream("null".getBytes(StandardCharsets.UTF_8))); // Lambda returns "null" on successful fn. with no return value
httpResponse.setEntity(responseBody);
try {
Mockito.doReturn(httpResponse).when(apacheHttpClient).execute(Mockito.any(HttpUriRequest.class), Mockito.any(HttpContext.class));
} catch (IOException e) { }
Whitebox.setInternalState(amazonHttpClient, "httpClient", apacheHttpClient);
Whitebox.setInternalState(lambda, "client", amazonHttpClient);
// Test logic
Segment segment = AWSXRay.beginSegment("test");
InvokeRequest request = new InvokeRequest();
request.setFunctionName("testFunctionName");
InvokeResult r = lambda.invoke(request);
System.out.println(r.getStatusCode());
System.out.println(r);
Assert.assertEquals(1, segment.getSubsegments().size());
Assert.assertEquals("Invoke", segment.getSubsegments().get(0).getAws().get("operation"));
System.out.println(segment.getSubsegments().get(0).getAws());
Assert.assertEquals("testFunctionName", segment.getSubsegments().get(0).getAws().get("function_name"));
}
示例11: getVersion
/**
* Obtains value of the {@link CoreProtocolPNames#PROTOCOL_VERSION} parameter.
* If not set, defaults to {@link HttpVersion#HTTP_1_1}.
*
* @param params HTTP parameters.
* @return HTTP protocol version.
*/
public static ProtocolVersion getVersion(final HttpParams params) {
if (params == null) {
throw new IllegalArgumentException("HTTP parameters may not be null");
}
Object param = params.getParameter
(CoreProtocolPNames.PROTOCOL_VERSION);
if (param == null) {
return HttpVersion.HTTP_1_1;
}
return (ProtocolVersion)param;
}
示例12: execute
@Override
public HttpResponse execute(HttpUriRequest request) throws IOException,
ClientProtocolException {
return new BasicHttpResponse(new BasicStatusLine(
HttpVersion.HTTP_1_1,
statusCode,
reasonPhrase));
}
示例13: testPostAuthForCookie
/**
* Tests the authentication post.
*/
private void testPostAuthForCookie(int responseStatus, String headerName, boolean isValidUser) throws IOException
{
HttpResponse fakeHttpResponse = new BasicHttpResponse(HttpVersion.HTTP_1_1, responseStatus, "some reason");
fakeHttpResponse.addHeader(headerName, COOKIE_VALUE);
fakeHttpResponse.setEntity(new StringEntity("{\"isLoggedIn\": " + isValidUser + "}"));
when(mockResponse.returnResponse()).thenReturn(fakeHttpResponse);
NameValuePair[] authParams = new NameValuePair[] {
new BasicNameValuePair("auth1", "hello"),
new BasicNameValuePair("auth2", "world")
};
httpHelper.postAuthForCookie(mockExecutor, URI, authParams);
}
示例14: testCacheEntryWithMustRevalidateDoesEndToEndRevalidation
@Test
public void testCacheEntryWithMustRevalidateDoesEndToEndRevalidation() throws Exception {
final HttpRequest basicRequest = new BasicHttpRequest("GET","/",HttpVersion.HTTP_1_1);
final HttpRequestWrapper requestWrapper = HttpRequestWrapper.wrap(basicRequest);
final Date now = new Date();
final Date elevenSecondsAgo = new Date(now.getTime() - 11 * 1000L);
final Date tenSecondsAgo = new Date(now.getTime() - 10 * 1000L);
final Date nineSecondsAgo = new Date(now.getTime() - 9 * 1000L);
final Header[] cacheEntryHeaders = new Header[] {
new BasicHeader("Date", DateUtils.formatDate(tenSecondsAgo)),
new BasicHeader("ETag", "\"etag\""),
new BasicHeader("Cache-Control","max-age=5, must-revalidate") };
final HttpCacheEntry cacheEntry = HttpTestUtils.makeCacheEntry(elevenSecondsAgo, nineSecondsAgo, cacheEntryHeaders);
final HttpRequest result = impl.buildConditionalRequest(requestWrapper, cacheEntry);
boolean foundMaxAge0 = false;
for(final Header h : result.getHeaders("Cache-Control")) {
for(final HeaderElement elt : h.getElements()) {
if ("max-age".equalsIgnoreCase(elt.getName())
&& "0".equals(elt.getValue())) {
foundMaxAge0 = true;
}
}
}
Assert.assertTrue(foundMaxAge0);
}
示例15: testReturns304ForIfNoneMatchHeaderAndIfModifiedSinceIfRequestServedFromCache
@Test
public void testReturns304ForIfNoneMatchHeaderAndIfModifiedSinceIfRequestServedFromCache()
throws Exception {
impl = createCachingExecChain(mockBackend, new BasicHttpCache(), CacheConfig.DEFAULT);
final Date now = new Date();
final Date tenSecondsAgo = new Date(now.getTime() - 10 * 1000L);
final HttpRequestWrapper req1 = HttpRequestWrapper.wrap(new HttpGet(
"http://foo.example.com/"));
final HttpRequestWrapper req2 = HttpRequestWrapper.wrap(new HttpGet(
"http://foo.example.com/"));
final HttpResponse resp1 = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_OK,
"OK");
resp1.setEntity(HttpTestUtils.makeBody(128));
resp1.setHeader("Content-Length", "128");
resp1.setHeader("ETag", "\"etag\"");
resp1.setHeader("Date", DateUtils.formatDate(tenSecondsAgo));
resp1.setHeader("Cache-Control", "public, max-age=3600");
resp1.setHeader("Last-Modified", DateUtils.formatDate(new Date()));
req2.addHeader("If-None-Match", "*");
req2.addHeader("If-Modified-Since", DateUtils.formatDate(now));
backendExpectsAnyRequestAndReturn(resp1);
replayMocks();
impl.execute(route, req1, context, null);
final HttpResponse result = impl.execute(route, req2, context, null);
verifyMocks();
Assert.assertEquals(HttpStatus.SC_NOT_MODIFIED, result.getStatusLine().getStatusCode());
}