private static HttpClient getNewHttpClient() { try { KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); trustStore.load(null, null); SSLSocketFactory sf = new SSLSocketFactoryEx(trustStore); sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); HttpParams params = new BasicHttpParams(); HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); HttpProtocolParams.setContentCharset(params, HTTP.UTF_8); SchemeRegistry registry = new SchemeRegistry(); registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80)); registry.register(new Scheme("https", sf, 443)); ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry); return new DefaultHttpClient(ccm, params); } catch (Exception e) { return new DefaultHttpClient(); } }
public static b a(String str) { HttpParams basicHttpParams = new BasicHttpParams(); HttpProtocolParams.setVersion(basicHttpParams, HttpVersion.HTTP_1_1); HttpProtocolParams.setUseExpectContinue(basicHttpParams, false); HttpConnectionParams.setStaleCheckingEnabled(basicHttpParams, false); HttpConnectionParams.setConnectionTimeout(basicHttpParams, 20000); HttpConnectionParams.setSoTimeout(basicHttpParams, 30000); HttpConnectionParams.setSocketBufferSize(basicHttpParams, 8192); HttpClientParams.setRedirecting(basicHttpParams, true); HttpClientParams.setAuthenticating(basicHttpParams, false); HttpProtocolParams.setUserAgent(basicHttpParams, str); SchemeRegistry schemeRegistry = new SchemeRegistry(); schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80)); schemeRegistry.register(new Scheme(com.alipay.sdk.cons.b.a, SSLCertificateSocketFactory.getHttpSocketFactory(30000, null), WebSocket.DEFAULT_WSS_PORT)); ClientConnectionManager threadSafeClientConnManager = new ThreadSafeClientConnManager(basicHttpParams, schemeRegistry); ConnManagerParams.setTimeout(basicHttpParams, 60000); ConnManagerParams.setMaxConnectionsPerRoute(basicHttpParams, new ConnPerRouteBean(10)); ConnManagerParams.setMaxTotalConnections(basicHttpParams, 50); Security.setProperty("networkaddress.cache.ttl", "-1"); HttpsURLConnection.setDefaultHostnameVerifier(SSLSocketFactory.STRICT_HOSTNAME_VERIFIER); return new b(threadSafeClientConnManager, basicHttpParams); }
/** * 设置默认请求参数,并返回HttpClient * * @return HttpClient */ private HttpClient createHttpClient() { HttpParams mDefaultHttpParams = new BasicHttpParams(); //设置连接超时 HttpConnectionParams.setConnectionTimeout(mDefaultHttpParams, 15000); //设置请求超时 HttpConnectionParams.setSoTimeout(mDefaultHttpParams, 15000); HttpConnectionParams.setTcpNoDelay(mDefaultHttpParams, true); HttpProtocolParams.setVersion(mDefaultHttpParams, HttpVersion.HTTP_1_1); HttpProtocolParams.setContentCharset(mDefaultHttpParams, HTTP.UTF_8); //持续握手 HttpProtocolParams.setUseExpectContinue(mDefaultHttpParams, true); HttpClient mHttpClient = new DefaultHttpClient(mDefaultHttpParams); return mHttpClient; }
public DefaultHttpClient getHttpClientInstance() { if (this.httpClient != null) { return this.httpClient; } HttpParams params = new BasicHttpParams(); params.setParameter("http.connection.timeout", CONNECTION_TIMEOUT); params.setParameter("http.socket.timeout", SOCKET_TIMEOUT); params.setParameter("http.protocol.version", HttpVersion.HTTP_1_1); params.setParameter("http.useragent", "Apache-HttpClient/Android"); params.setParameter("http.connection.stalecheck", Boolean.valueOf(false)); this.httpClient = new DefaultHttpClient(params); this.httpClient.addRequestInterceptor(new GzipHttpRequestInterceptor()); this.httpClient.addResponseInterceptor(new GzipHttpResponseInterceptor()); this.httpClient.setHttpRequestRetryHandler(new DefaultHttpRequestRetryHandler(0, false)); return this.httpClient; }
public HttpResponse execute(HttpRequest request) throws IOException, HttpException { HttpParams params = new BasicHttpParams(); HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); HttpProcessor processor = new ImmutableHttpProcessor(new RequestContent()); HttpRequestExecutor executor = new HttpRequestExecutor(); HttpContext context = new BasicHttpContext(null); context.setAttribute(ExecutionContext.HTTP_CONNECTION, connection); if (!connection.isOpen()) { Socket socket = new Socket(address.getAddress(), address.getPort()); connection.bind(socket, params); } context.setAttribute(ExecutionContext.HTTP_REQUEST, request); request.setParams(params); executor.preProcess(request, processor, context); HttpResponse response = executor.execute(request, connection, context); executor.postProcess(response, processor, context); return response; }
@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 HttpParams createHttpParams() { HttpParams params = new BasicHttpParams(); HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); HttpProtocolParams.setContentCharset(params, "UTF-8"); HttpProtocolParams.setUseExpectContinue(params, false); ConnManagerParams.setMaxConnectionsPerRoute(params, new ConnPerRouteBean(3)); ConnManagerParams.setMaxTotalConnections(params, 3); ConnManagerParams.setTimeout(params, 1000); HttpConnectionParams.setConnectionTimeout(params, 30000); HttpConnectionParams.setSoTimeout(params, 30000); HttpConnectionParams.setStaleCheckingEnabled(params, false); HttpConnectionParams.setTcpNoDelay(params, true); HttpConnectionParams.setSocketBufferSize(params, 8192); HttpClientParams.setRedirecting(params, false); return params; }
public synchronized static DefaultHttpClient getHttpClient() { try { HttpParams params = new BasicHttpParams(); // 设置一些基本参数 HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); // 超时设置 // 从连接池中取连接的超时时间 ConnManagerParams.setTimeout(params, 10000); // 连接超时 HttpConnectionParams.setConnectionTimeout(params, 10000); // 请求超时 HttpConnectionParams.setSoTimeout(params, 30000); SchemeRegistry registry = new SchemeRegistry(); Scheme sch1 = new Scheme("http", PlainSocketFactory .getSocketFactory(), 80); registry.register(sch1); // 使用线程安全的连接管理来创建HttpClient ClientConnectionManager conMgr = new ThreadSafeClientConnManager( params, registry); mHttpClient = new DefaultHttpClient(conMgr, params); } catch (Exception e) { e.printStackTrace(); } return mHttpClient; }
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 void process(final HttpRequest request, final HttpContext context) throws HttpException, IOException { if (request == null) { throw new IllegalArgumentException("HTTP request may not be null"); } if (request instanceof HttpEntityEnclosingRequest) { HttpEntity entity = ((HttpEntityEnclosingRequest)request).getEntity(); // Do not send the expect header if request body is known to be empty if (entity != null && entity.getContentLength() != 0) { ProtocolVersion ver = request.getRequestLine().getProtocolVersion(); if (HttpProtocolParams.useExpectContinue(request.getParams()) && !ver.lessEquals(HttpVersion.HTTP_1_0)) { request.addHeader(HTTP.EXPECT_DIRECTIVE, HTTP.EXPECT_CONTINUE); } } } }
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); } }
/** * 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++; } }
/** * Gets a DefaultHttpClient which trusts a set of certificates specified by the KeyStore * * @param keyStore custom provided KeyStore instance * @return DefaultHttpClient */ public static DefaultHttpClient getNewHttpClient(KeyStore keyStore) { try { SSLSocketFactory sf = new MySSLSocketFactory(keyStore); SchemeRegistry registry = new SchemeRegistry(); registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80)); registry.register(new Scheme("https", sf, 443)); HttpParams params = new BasicHttpParams(); HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); HttpProtocolParams.setContentCharset(params, HTTP.UTF_8); ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry); return new DefaultHttpClient(ccm, params); } catch (Exception e) { return new DefaultHttpClient(); } }
public static SchemeRegistry getSchemeRegistry() { try { KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); trustStore.load(null, null); SSLSocketFactory.getSocketFactory().setHostnameVerifier(new AllowAllHostnameVerifier()); SSLSocketFactory sf = new SSLSocketFactory(trustStore); sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); HttpParams params = new BasicHttpParams(); HttpConnectionParams.setConnectionTimeout(params, 10000); HttpConnectionParams.setSoTimeout(params, 10000); HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); HttpProtocolParams.setContentCharset(params, HTTP.UTF_8); SchemeRegistry registry = new SchemeRegistry(); registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80)); registry.register(new Scheme("https", sf, 443)); return registry; } catch (Exception e) { return null; } }
/** * Gets getUrl DefaultHttpClient which trusts getUrl set of certificates specified by the KeyStore * * @param keyStore custom provided KeyStore instance * @return DefaultHttpClient */ public static DefaultHttpClient getNewHttpClient(KeyStore keyStore) { try { SSLSocketFactory sf = new MySSLSocketFactory(keyStore); SchemeRegistry registry = new SchemeRegistry(); registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80)); registry.register(new Scheme("https", sf, 443)); HttpParams params = new BasicHttpParams(); HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); HttpProtocolParams.setContentCharset(params, HTTP.UTF_8); ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry); return new DefaultHttpClient(ccm, params); } catch (Exception e) { return new DefaultHttpClient(); } }
@Test public void downloadNewStatementsClosesEntityStream() throws Exception { final Config filesStep = ConfigFactory.parseString("{ method = get, path = /files }"); final CloseableHttpResponse response = mock(CloseableHttpResponse.class); final HttpEntity entity = mock(HttpEntity.class); final InputStream stream = mock(InputStream.class); doReturn(Collections.singletonList(filesStep)).when(config).getConfigList("fileList"); when(client.execute(any(HttpGet.class))).thenReturn(response); when(response.getStatusLine()).thenReturn(new BasicStatusLine(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, null)); when(response.getEntity()).thenReturn(entity); when(entity.isStreaming()).thenReturn(true); when(entity.getContent()).thenReturn(stream); download.downloadNewStatements(); verify(response).getEntity(); verify(entity).getContent(); verify(stream).close(); }
@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(); }
@Test public void testAuthenticationHandshaking() throws Exception { final HttpHost host = new HttpHost("somehost", 80); final HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_UNAUTHORIZED, "UNAUTHORIZED"); response.addHeader(new BasicHeader(AUTH.WWW_AUTH, "Basic realm=\"test\"")); response.addHeader(new BasicHeader(AUTH.WWW_AUTH, "Digest realm=\"realm1\", stale=true, nonce=\"1234\"")); response.addHeader(new BasicHeader(AUTH.WWW_AUTH, "whatever realm=\"realm1\", stuff=\"1234\"")); final TargetAuthenticationStrategy authStrategy = new TargetAuthenticationStrategy(); this.authState.setState(AuthProtocolState.CHALLENGED); this.authState.update(new DigestScheme(), this.credentials); Assert.assertTrue(this.httpAuthenticator.handleAuthChallenge(host, response, authStrategy, this.authState, this.context)); Assert.assertEquals(AuthProtocolState.HANDSHAKE, this.authState.getState()); }
private DefaultHttpClient createHttpClient() { HttpParams params = new BasicHttpParams(); HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); HttpProtocolParams.setContentCharset(params, HTTP.DEFAULT_CONTENT_CHARSET); HttpProtocolParams.setUseExpectContinue(params, true); HttpConnectionParams.setConnectionTimeout(params, CONNETED_TIMEOUT * 1000); HttpConnectionParams.setSoTimeout(params, CONNETED_TIMEOUT * 1000); HttpConnectionParams.setSocketBufferSize(params, 8192); ConnManagerParams.setMaxTotalConnections(params, 4); SchemeRegistry schReg = new SchemeRegistry(); schReg.register(new Scheme("http", PlainSocketFactory .getSocketFactory(), 80)); schReg.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443)); ClientConnectionManager connMgr = new ThreadSafeClientConnManager( params, schReg); return new DefaultHttpClient(connMgr, params); }
private void testRequestIsWrittenThroughToOrigin(final HttpRequest req) throws Exception { final HttpResponse resp = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_NO_CONTENT, "No Content"); final HttpRequestWrapper wrapper = HttpRequestWrapper.wrap(req); EasyMock.expect( mockBackend.execute( EasyMock.eq(route), eqRequest(wrapper), EasyMock.isA(HttpClientContext.class), EasyMock.<HttpExecutionAware>isNull())).andReturn( Proxies.enhanceResponse(resp)); replayMocks(); impl.execute(route, wrapper, context, null); verifyMocks(); }
@Test public void testSetsViaHeaderOnResponseIfRequestNotServableFromCache() throws Exception { impl = createCachingExecChain(mockBackend, new BasicHttpCache(), CacheConfig.DEFAULT); final HttpRequestWrapper req = HttpRequestWrapper.wrap(new HttpGet( "http://foo.example.com/")); req.setHeader("Cache-Control", "no-cache"); final HttpResponse resp = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_NO_CONTENT, "No Content"); backendExpectsAnyRequestAndReturn(resp); replayMocks(); final HttpResponse result = impl.execute(route, req, context, null); verifyMocks(); Assert.assertNotNull(result.getFirstHeader("Via")); }
@Test public void test206ContainsContentLocationIfA200ResponseWouldHaveIncludedIt() throws Exception { final HttpRequestWrapper req1 = HttpRequestWrapper.wrap( new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_1)); originResponse.addHeader("Cache-Control", "max-age=3600"); originResponse.addHeader("Content-Location", "http://foo.example.com/other/url"); final HttpRequestWrapper req2 = HttpRequestWrapper.wrap( new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_1)); req2.addHeader("Range", "bytes=0-50"); backendExpectsAnyRequest().andReturn(originResponse).times(1, 2); replayMocks(); impl.execute(route, req1, context, null); final HttpResponse result = impl.execute(route, req2, context, null); verifyMocks(); if (result.getStatusLine().getStatusCode() == HttpStatus.SC_PARTIAL_CONTENT) { Assert.assertNotNull(result.getFirstHeader("Content-Location")); } }
@Test public void testRecordsClientProtocolInViaHeaderIfRequestNotServableFromCache() throws Exception { impl = createCachingExecChain(mockBackend, new BasicHttpCache(), CacheConfig.DEFAULT); final HttpRequestWrapper req = HttpRequestWrapper.wrap(new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_0)); req.setHeader("Cache-Control", "no-cache"); final HttpResponse resp = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_NO_CONTENT, "No Content"); final Capture<HttpRequestWrapper> cap = new Capture<HttpRequestWrapper>(); backendCaptureRequestAndReturn(cap, resp); replayMocks(); impl.execute(route, req, context, null); verifyMocks(); final HttpRequest captured = cap.getValue(); final String via = captured.getFirstHeader("Via").getValue(); final String proto = via.split("\\s+")[0]; Assert.assertTrue("http/1.0".equalsIgnoreCase(proto) || "1.0".equalsIgnoreCase(proto)); }
/** * Performs general setup. * This should be called only once. */ private final static void setup() { // Register the "http" and "https" protocol schemes, they are // required by the default operator to look up socket factories. supportedSchemes = new SchemeRegistry(); SocketFactory sf = PlainSocketFactory.getSocketFactory(); supportedSchemes.register(new Scheme("http", sf, 80)); sf = SSLSocketFactory.getSocketFactory(); supportedSchemes.register(new Scheme("https", sf, 80)); // Prepare parameters. // Since this example doesn't use the full core framework, // only few parameters are actually required. HttpParams params = new BasicHttpParams(); HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); HttpProtocolParams.setUseExpectContinue(params, false); defaultParameters = params; }
@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()); }
@Test public void test206ResponseGeneratedFromCacheMustHaveDateHeader() throws Exception { final HttpRequestWrapper req1 = HttpRequestWrapper.wrap( new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_1)); final HttpResponse resp1 = HttpTestUtils.make200Response(); resp1.setHeader("ETag", "\"etag\""); resp1.setHeader("Cache-Control", "max-age=3600"); final HttpRequestWrapper req2 = HttpRequestWrapper.wrap( new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_1)); req2.setHeader("Range", "bytes=0-50"); backendExpectsAnyRequestAndReturn(resp1).times(1, 2); replayMocks(); impl.execute(route, req1, context, null); final HttpResponse result = impl.execute(route, req2, context, null); verifyMocks(); if (HttpStatus.SC_PARTIAL_CONTENT == result.getStatusLine().getStatusCode()) { Assert.assertNotNull(result.getFirstHeader("Date")); } }
@Test public void testResponseParsingWithSomeGarbage() throws Exception { final String s = "garbage\r\n" + "garbage\r\n" + "more garbage\r\n" + "HTTP/1.1 200 OK\r\n" + "header1: value1\r\n" + "header2: value2\r\n" + "\r\n"; final SessionInputBuffer inbuffer = new SessionInputBufferMock(s, Consts.ASCII); final HttpMessageParser<HttpResponse> parser = new DefaultHttpResponseParser(inbuffer); final HttpResponse response = parser.parse(); Assert.assertNotNull(response); Assert.assertEquals(HttpVersion.HTTP_1_1, response.getProtocolVersion()); Assert.assertEquals(200, response.getStatusLine().getStatusCode()); final Header[] headers = response.getAllHeaders(); Assert.assertNotNull(headers); Assert.assertEquals(2, headers.length); Assert.assertEquals("header1", headers[0].getName()); Assert.assertEquals("header2", headers[1].getName()); }
@Test public void testSmallEnoughResponsesAreCached() throws Exception { final HttpHost host = new HttpHost("foo.example.com"); final HttpRequest request = new HttpGet("http://foo.example.com/bar"); final Date now = new Date(); final Date requestSent = new Date(now.getTime() - 3 * 1000L); final Date responseGenerated = new Date(now.getTime() - 2 * 1000L); final Date responseReceived = new Date(now.getTime() - 1 * 1000L); final HttpResponse originResponse = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, "OK"); originResponse.setEntity(HttpTestUtils.makeBody(CacheConfig.DEFAULT_MAX_OBJECT_SIZE_BYTES - 1)); originResponse.setHeader("Cache-Control","public, max-age=3600"); originResponse.setHeader("Date", DateUtils.formatDate(responseGenerated)); originResponse.setHeader("ETag", "\"etag\""); final HttpResponse result = impl.cacheAndReturnResponse(host, request, originResponse, requestSent, responseReceived); assertEquals(1, backing.map.size()); assertTrue(backing.map.containsKey((new CacheKeyGenerator()).getURI(host, request))); assertTrue(HttpTestUtils.semanticallyTransparent(originResponse, result)); }
@Test public void testMustIncludeWWWAuthenticateHeaderOnAnOrigin401Response() throws Exception { originResponse = Proxies.enhanceResponse( new BasicHttpResponse(HttpVersion.HTTP_1_1, 401, "Unauthorized")); originResponse.setHeader("WWW-Authenticate", "x-scheme x-param"); EasyMock.expect( mockBackend.execute( EasyMock.isA(HttpRoute.class), EasyMock.isA(HttpRequestWrapper.class), EasyMock.isA(HttpClientContext.class), EasyMock.<HttpExecutionAware>isNull())).andReturn(originResponse); replayMocks(); final HttpResponse result = impl.execute(route, request, context, null); if (result.getStatusLine().getStatusCode() == 401) { Assert.assertNotNull(result.getFirstHeader("WWW-Authenticate")); } verifyMocks(); }
@Before public void initExecutor() throws IOException { SelfCloseableHttpClient httpMock = mock(SelfCloseableHttpClient.class); when(httpMock.execute(any())).thenAnswer(invocationOnMock -> { HttpGet get = (HttpGet) invocationOnMock.getArguments()[0]; mockLog.append(get.getMethod()).append(" ").append(get.getURI()).append(" "); if (mockReturnCode == 100000) throw new RuntimeException("FAIL"); BasicStatusLine statusLine = new BasicStatusLine(HttpVersion.HTTP_1_1, mockReturnCode, null); BasicHttpEntity entity = new BasicHttpEntity(); String returnMessage = "{\"foo\":\"bar\", \"no\":3, \"error-code\": " + mockReturnCode + "}"; InputStream stream = new ByteArrayInputStream(returnMessage.getBytes(StandardCharsets.UTF_8)); entity.setContent(stream); CloseableHttpResponse response = mock(CloseableHttpResponse.class); when(response.getEntity()).thenReturn(entity); when(response.getStatusLine()).thenReturn(statusLine); return response; }); executor = new ConfigServerHttpRequestExecutor(configServers, httpMock); }
@Test public void testAuthenticationNotRequestedSuccess1() throws Exception { final HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, "OK"); Mockito.when(this.defltAuthStrategy.isAuthenticationRequested( Mockito.any(HttpHost.class), Mockito.any(HttpResponse.class), Mockito.any(HttpContext.class))).thenReturn(Boolean.FALSE); this.authState.update(this.authScheme, this.credentials); this.authState.setState(AuthProtocolState.CHALLENGED); Assert.assertFalse(this.httpAuthenticator.isAuthenticationRequested( this.defaultHost, response, this.defltAuthStrategy, this.authState, this.context)); Assert.assertEquals(AuthProtocolState.SUCCESS, this.authState.getState()); Mockito.verify(this.defltAuthStrategy).isAuthenticationRequested(this.defaultHost, response, this.context); Mockito.verify(this.defltAuthStrategy).authSucceeded(this.defaultHost, this.authScheme, this.context); }
@Test public void testExpiresHeaderEqualToDateHeaderIsTreatedAsStale() throws Exception { final HttpRequestWrapper req1 = HttpRequestWrapper.wrap( new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_1)); final HttpResponse resp1 = HttpTestUtils.make200Response(); resp1.setHeader("Cache-Control","public"); resp1.setHeader("ETag","\"etag\""); resp1.setHeader("Expires", resp1.getFirstHeader("Date").getValue()); final HttpRequestWrapper req2 = HttpRequestWrapper.wrap( new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_1)); final HttpResponse resp2 = HttpTestUtils.make200Response(); backendExpectsAnyRequestAndReturn(resp1); // second request to origin MUST happen backendExpectsAnyRequestAndReturn(resp2); replayMocks(); impl.execute(route, req1, context, null); impl.execute(route, req2, context, null); verifyMocks(); }
@Test public void testNoCookieStore() 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, this.cookieSpec); context.setAttribute(HttpClientContext.COOKIE_STORE, null); final HttpResponseInterceptor interceptor = new ResponseProcessCookies(); interceptor.process(response, context); final List<Cookie> cookies = this.cookieStore.getCookies(); Assert.assertNotNull(cookies); Assert.assertEquals(0, cookies.size()); }
@Test public void testForwardsUnknownHeadersOnRequestsFromHigherProtocolVersions() throws Exception { request = HttpRequestWrapper.wrap( new BasicHttpRequest("GET", "/foo", new ProtocolVersion("HTTP", 1, 2))); request.removeHeaders("Connection"); request.addHeader("X-Unknown-Header", "some-value"); final HttpRequestWrapper downgraded = HttpRequestWrapper.wrap( new BasicHttpRequest("GET", "/foo", HttpVersion.HTTP_1_1)); downgraded.removeHeaders("Connection"); downgraded.addHeader("X-Unknown-Header", "some-value"); EasyMock.expect( mockBackend.execute( EasyMock.isA(HttpRoute.class), eqRequest(downgraded), EasyMock.isA(HttpClientContext.class), EasyMock.<HttpExecutionAware>isNull())).andReturn(originResponse); replayMocks(); impl.execute(route, request, context, null); verifyMocks(); }
@Test public void testHigher1_XProtocolVersionsDowngradeTo1_1() throws Exception { request = HttpRequestWrapper.wrap( new BasicHttpRequest("GET", "/foo", new ProtocolVersion("HTTP", 1, 2))); final HttpRequestWrapper downgraded = HttpRequestWrapper.wrap( new BasicHttpRequest("GET", "/foo", HttpVersion.HTTP_1_1)); EasyMock.expect( mockBackend.execute( EasyMock.eq(route), eqRequest(downgraded), EasyMock.isA(HttpClientContext.class), EasyMock.<HttpExecutionAware>isNull())).andReturn(originResponse); replayMocks(); final HttpResponse result = impl.execute(route, request, context, null); verifyMocks(); Assert.assertTrue(HttpTestUtils.semanticallyTransparent(originResponse, result)); }
@Test public void testAuthenticationNotRequestedSuccess2() throws Exception { final HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, "OK"); Mockito.when(this.defltAuthStrategy.isAuthenticationRequested( Mockito.any(HttpHost.class), Mockito.any(HttpResponse.class), Mockito.any(HttpContext.class))).thenReturn(Boolean.FALSE); this.authState.update(this.authScheme, this.credentials); this.authState.setState(AuthProtocolState.HANDSHAKE); Assert.assertFalse(this.httpAuthenticator.isAuthenticationRequested( this.defaultHost, response, this.defltAuthStrategy, this.authState, this.context)); Assert.assertEquals(AuthProtocolState.SUCCESS, this.authState.getState()); Mockito.verify(this.defltAuthStrategy).isAuthenticationRequested(this.defaultHost, response, this.context); Mockito.verify(this.defltAuthStrategy).authSucceeded(this.defaultHost, this.authScheme, this.context); }