当前位置: 首页>>代码示例>>Java>>正文


Java HttpVersion.HTTP_1_1属性代码示例

本文整理汇总了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());
    }
}
 
开发者ID:rpgreen,项目名称:apigateway-generic-java-sdk,代码行数:26,代码来源:GenericApiGatewayClientTest.java

示例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;
}
 
开发者ID:aws,项目名称:aws-xray-sdk-java,代码行数:18,代码来源:TracedResponseHandlerTest.java

示例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);

    }
}
 
开发者ID:renatoathaydes,项目名称:rawhttp,代码行数:16,代码来源:RawHttpComponentsClient.java

示例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++;
	}
}
 
开发者ID:ligoj,项目名称:bootstrap,代码行数:24,代码来源:AbstractRestTest.java

示例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);
}
 
开发者ID:MyPureCloud,项目名称:purecloud-iot,代码行数:21,代码来源:TestResponseProtocolCompliance.java

示例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());
}
 
开发者ID:MyPureCloud,项目名称:purecloud-iot,代码行数:19,代码来源:TestHttpAuthenticator.java

示例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());
}
 
开发者ID:MyPureCloud,项目名称:purecloud-iot,代码行数:17,代码来源:TestResponseProcessCookies.java

示例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();
}
 
开发者ID:MyPureCloud,项目名称:purecloud-iot,代码行数:23,代码来源:TestAbstractResponseHandler.java

示例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();
}
 
开发者ID:rpgreen,项目名称:apigateway-generic-java-sdk,代码行数:22,代码来源:GenericApiGatewayClientTest.java

示例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"));
}
 
开发者ID:aws,项目名称:aws-xray-sdk-java,代码行数:33,代码来源:TracingHandlerTest.java

示例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;
}
 
开发者ID:lamsfoundation,项目名称:lams,代码行数:18,代码来源:HttpProtocolParams.java

示例12: execute

@Override
public HttpResponse execute(HttpUriRequest request) throws IOException,
        ClientProtocolException {
    return new BasicHttpResponse(new BasicStatusLine(
            HttpVersion.HTTP_1_1,
            statusCode,
            reasonPhrase));
}
 
开发者ID:IBM,项目名称:ibm-cos-sdk-java,代码行数:8,代码来源:RetryPolicyTestBase.java

示例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);
}
 
开发者ID:Nike-Inc,项目名称:bluegreen-manager,代码行数:16,代码来源:HttpHelperTest.java

示例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);
}
 
开发者ID:MyPureCloud,项目名称:purecloud-iot,代码行数:28,代码来源:TestConditionalRequestBuilder.java

示例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());

}
 
开发者ID:MyPureCloud,项目名称:purecloud-iot,代码行数:32,代码来源:TestCachingExecChain.java


注:本文中的org.apache.http.HttpVersion.HTTP_1_1属性示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。