public HttpRequest newHttpRequest(final RequestLine requestline) throws MethodNotSupportedException { if (requestline == null) { throw new IllegalArgumentException("Request line may not be null"); } String method = requestline.getMethod(); if (isOneOf(RFC2616_COMMON_METHODS, method)) { return new BasicHttpRequest(requestline); } else if (isOneOf(RFC2616_ENTITY_ENC_METHODS, method)) { return new BasicHttpEntityEnclosingRequest(requestline); } else if (isOneOf(RFC2616_SPECIAL_METHODS, method)) { return new BasicHttpRequest(requestline); } else { throw new MethodNotSupportedException(method + " method not supported"); } }
@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)); }
@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)); }
@Test public void testDigestAuthenticationWithQueryStringInDigestURI() throws Exception { final String challenge = "Digest realm=\"realm1\", nonce=\"f2a3f18799759d4f1a1c068b92b573cb\""; final Header authChallenge = new BasicHeader(AUTH.WWW_AUTH, challenge); final HttpRequest request = new BasicHttpRequest("Simple", "/?param=value"); final Credentials cred = new UsernamePasswordCredentials("username","password"); final HttpContext context = new BasicHttpContext(); final DigestScheme authscheme = new DigestScheme(); authscheme.processChallenge(authChallenge); final Header authResponse = authscheme.authenticate(cred, request, context); final Map<String, String> table = parseAuthResponse(authResponse); Assert.assertEquals("username", table.get("username")); Assert.assertEquals("realm1", table.get("realm")); Assert.assertEquals("/?param=value", table.get("uri")); Assert.assertEquals("f2a3f18799759d4f1a1c068b92b573cb", table.get("nonce")); Assert.assertEquals("a847f58f5fef0bc087bcb9c3eb30e042", table.get("response")); }
public HttpRequest submitRequest(final HttpContext context) { HttpHost targetHost = (HttpHost) context.getAttribute( ExecutionContext.HTTP_TARGET_HOST); Object flag = context.getAttribute(REQUEST_SENT); if (flag == null) { // Stick some object into the context context.setAttribute(REQUEST_SENT, Boolean.TRUE); System.out.println("--------------"); System.out.println("Sending request to " + targetHost); System.out.println("--------------"); return new BasicHttpRequest("GET", "/"); } else { // No new request to submit return null; } }
@Test public void testAuthCacheEmpty() throws Exception { final HttpRequest request = new BasicHttpRequest("GET", "/"); final HttpClientContext context = HttpClientContext.create(); context.setAttribute(HttpClientContext.CREDS_PROVIDER, this.credProvider); context.setAttribute(HttpCoreContext.HTTP_TARGET_HOST, this.target); context.setAttribute(HttpClientContext.HTTP_ROUTE, new HttpRoute(this.target, null, this.proxy, false)); context.setAttribute(HttpClientContext.TARGET_AUTH_STATE, this.targetState); context.setAttribute(HttpClientContext.PROXY_AUTH_STATE, this.proxyState); final AuthCache authCache = new BasicAuthCache(); context.setAttribute(HttpClientContext.AUTH_CACHE, authCache); final HttpRequestInterceptor interceptor = new RequestAuthCache(); interceptor.process(request, context); Assert.assertNull(this.targetState.getAuthScheme()); Assert.assertNull(this.targetState.getCredentials()); Assert.assertNull(this.proxyState.getAuthScheme()); Assert.assertNull(this.proxyState.getCredentials()); }
@Test public void testAddCookiesUsingExplicitCookieSpec() throws Exception { final HttpRequest request = new BasicHttpRequest("GET", "/"); final RequestConfig config = RequestConfig.custom() .setCookieSpec(CookieSpecs.NETSCAPE).build(); final HttpRoute route = new HttpRoute(this.target, null, false); final HttpClientContext context = HttpClientContext.create(); context.setAttribute(HttpCoreContext.HTTP_TARGET_HOST, this.target); context.setAttribute(HttpClientContext.HTTP_ROUTE, route); context.setAttribute(HttpClientContext.REQUEST_CONFIG, config); context.setAttribute(HttpClientContext.COOKIE_STORE, this.cookieStore); context.setAttribute(HttpClientContext.COOKIESPEC_REGISTRY, this.cookieSpecRegistry); final HttpRequestInterceptor interceptor = new RequestAddCookies(); interceptor.process(request, context); final CookieSpec cookieSpec = context.getCookieSpec(); Assert.assertTrue(cookieSpec instanceof NetscapeDraftSpec); final Header[] headers1 = request.getHeaders(SM.COOKIE); Assert.assertNotNull(headers1); Assert.assertEquals(1, headers1.length); Assert.assertEquals("name1=value1; name2=value2", headers1[0].getValue()); }
@Test public void testExpiresHeaderMatchesDateIfAddedToCacheHit() throws Exception { final HttpRequestWrapper req1 = HttpRequestWrapper.wrap( new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_1)); final HttpRequestWrapper req2 = HttpRequestWrapper.wrap( new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_1)); originResponse.setHeader("Cache-Control","max-age=3600"); originResponse.removeHeaders("Expires"); backendExpectsAnyRequest().andReturn(originResponse); replayMocks(); impl.execute(route, req1, context, null); final HttpResponse result = impl.execute(route, req2, context, null); verifyMocks(); final Header expHdr = result.getFirstHeader("Expires"); if (expHdr != null) { Assert.assertEquals(result.getFirstHeader("Date").getValue(), expHdr.getValue()); } }
@Test public void testNoTargetHost() throws Exception { final HttpRequest request = new BasicHttpRequest("GET", "/"); final HttpRoute route = new HttpRoute(this.target, null, false); final HttpClientContext context = HttpClientContext.create(); context.setAttribute(HttpCoreContext.HTTP_TARGET_HOST, null); context.setAttribute(HttpClientContext.HTTP_ROUTE, route); context.setAttribute(HttpClientContext.COOKIE_STORE, this.cookieStore); context.setAttribute(HttpClientContext.COOKIESPEC_REGISTRY, this.cookieSpecRegistry); final HttpRequestInterceptor interceptor = new RequestAddCookies(); interceptor.process(request, context); final Header[] headers1 = request.getHeaders(SM.COOKIE); Assert.assertNotNull(headers1); Assert.assertEquals(0, headers1.length); final Header[] headers2 = request.getHeaders(SM.COOKIE2); Assert.assertNotNull(headers2); Assert.assertEquals(0, headers2.length); }
@Test public void testMayReturnStaleResponseIfClientExplicitlySpecifiesAcceptableMaxStale() throws Exception { final HttpRequestWrapper req1 = requestToPopulateStaleCacheEntry(); final HttpRequestWrapper req2 = HttpRequestWrapper.wrap( new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_1)); req2.setHeader("Cache-Control","max-stale=20"); backendExpectsAnyRequest().andThrow(new IOException()).times(0,1); replayMocks(); impl.execute(route, req1, context, null); final HttpResponse result = impl.execute(route, req2, context, null); verifyMocks(); assertEquals(HttpStatus.SC_OK, result.getStatusLine().getStatusCode()); assertNotNull(result.getFirstHeader("Warning")); }
@Test public void testPreemptiveTargetAndProxyAuth() throws Exception { final HttpRequest request = new BasicHttpRequest("GET", "/"); final HttpClientContext context = HttpClientContext.create(); context.setAttribute(HttpClientContext.CREDS_PROVIDER, this.credProvider); context.setAttribute(HttpCoreContext.HTTP_TARGET_HOST, this.target); context.setAttribute(HttpClientContext.HTTP_ROUTE, new HttpRoute(this.target, null, this.proxy, false)); context.setAttribute(HttpClientContext.TARGET_AUTH_STATE, this.targetState); context.setAttribute(HttpClientContext.PROXY_AUTH_STATE, this.proxyState); final AuthCache authCache = new BasicAuthCache(); authCache.put(this.target, this.authscheme1); authCache.put(this.proxy, this.authscheme2); context.setAttribute(HttpClientContext.AUTH_CACHE, authCache); final HttpRequestInterceptor interceptor = new RequestAuthCache(); interceptor.process(request, context); Assert.assertNotNull(this.targetState.getAuthScheme()); Assert.assertSame(this.creds1, this.targetState.getCredentials()); Assert.assertNotNull(this.proxyState.getAuthScheme()); Assert.assertSame(this.creds2, this.proxyState.getCredentials()); }
@Test public void testNoCacheCannotSatisfyASubsequentRequestWithoutRevalidationEvenWithContraryIndications() 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","no-cache,s-maxage=3600"); backendExpectsAnyRequestAndReturn(resp1); final HttpRequestWrapper req2 = HttpRequestWrapper.wrap( new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_1)); req2.setHeader("Cache-Control","max-stale=7200"); final HttpResponse resp2 = HttpTestUtils.make200Response(); // this MUST happen backendExpectsAnyRequestAndReturn(resp2); replayMocks(); impl.execute(route, req1, context, null); impl.execute(route, req2, context, null); verifyMocks(); }
@Test public void testCacheControlPrivateIsNotCacheableBySharedCache() throws Exception { if (config.isSharedCache()) { final HttpRequestWrapper req1 = HttpRequestWrapper.wrap( new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_1)); final HttpResponse resp1 = HttpTestUtils.make200Response(); resp1.setHeader("Cache-Control","private,max-age=3600"); backendExpectsAnyRequestAndReturn(resp1); final HttpRequestWrapper req2 = HttpRequestWrapper.wrap( new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_1)); final HttpResponse resp2 = HttpTestUtils.make200Response(); // this backend request MUST happen backendExpectsAnyRequestAndReturn(resp2); replayMocks(); impl.execute(route, req1, context, null); impl.execute(route, req2, context, null); verifyMocks(); } }
@Test public void testCookiesForConnectRequest() throws Exception { final HttpRequest request = new BasicHttpRequest("CONNECT", "www.somedomain.com"); final HttpRoute route = new HttpRoute(this.target, null, false); final HttpClientContext context = HttpClientContext.create(); context.setAttribute(HttpCoreContext.HTTP_TARGET_HOST, this.target); context.setAttribute(HttpClientContext.HTTP_ROUTE, route); context.setAttribute(HttpClientContext.COOKIE_STORE, this.cookieStore); context.setAttribute(HttpClientContext.COOKIESPEC_REGISTRY, this.cookieSpecRegistry); final HttpRequestInterceptor interceptor = new RequestAddCookies(); interceptor.process(request, context); final Header[] headers1 = request.getHeaders(SM.COOKIE); Assert.assertNotNull(headers1); Assert.assertEquals(0, headers1.length); final Header[] headers2 = request.getHeaders(SM.COOKIE2); Assert.assertNotNull(headers2); Assert.assertEquals(0, headers2.length); }
@Test public void testNoMatchingCredentials() throws Exception { final HttpRequest request = new BasicHttpRequest("GET", "/"); this.credProvider.clear(); final HttpClientContext context = HttpClientContext.create(); context.setAttribute(HttpClientContext.CREDS_PROVIDER, this.credProvider); context.setAttribute(HttpCoreContext.HTTP_TARGET_HOST, this.target); context.setAttribute(HttpClientContext.HTTP_ROUTE, new HttpRoute(this.target, null, this.proxy, false)); context.setAttribute(HttpClientContext.TARGET_AUTH_STATE, this.targetState); context.setAttribute(HttpClientContext.PROXY_AUTH_STATE, this.proxyState); final AuthCache authCache = new BasicAuthCache(); authCache.put(this.target, this.authscheme1); authCache.put(this.proxy, this.authscheme2); context.setAttribute(HttpClientContext.AUTH_CACHE, authCache); final HttpRequestInterceptor interceptor = new RequestAuthCache(); interceptor.process(request, context); Assert.assertNull(this.targetState.getAuthScheme()); Assert.assertNull(this.targetState.getCredentials()); Assert.assertNull(this.proxyState.getAuthScheme()); Assert.assertNull(this.proxyState.getCredentials()); }
@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)); }
@Test public void testConditionalRequestForEntryWithLastModifiedAndEtagIncludesBothAsValidators() throws Exception { final Date now = new Date(); final Date tenSecondsAgo = new Date(now.getTime() - 10 * 1000L); final Date twentySecondsAgo = new Date(now.getTime() - 20 * 1000L); final String lmDate = DateUtils.formatDate(twentySecondsAgo); final String etag = "\"etag\""; final Header[] headers = { new BasicHeader("Date", DateUtils.formatDate(tenSecondsAgo)), new BasicHeader("Last-Modified", lmDate), new BasicHeader("ETag", etag) }; final HttpRequest basicRequest = new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_1); final HttpRequestWrapper requestWrapper = HttpRequestWrapper.wrap(basicRequest); final HttpCacheEntry cacheEntry = HttpTestUtils.makeCacheEntry(headers); final HttpRequest result = impl.buildConditionalRequest(requestWrapper, cacheEntry); Assert.assertEquals(lmDate, result.getFirstHeader("If-Modified-Since").getValue()); Assert.assertEquals(etag, result.getFirstHeader("If-None-Match").getValue()); }
private void testDoesNotModifyHeaderFromOriginOnCacheHit(final String header, final String value) throws Exception { final HttpRequestWrapper req1 = HttpRequestWrapper.wrap( new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_1)); final HttpRequestWrapper req2 = HttpRequestWrapper.wrap( new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_1)); originResponse = Proxies.enhanceResponse(HttpTestUtils.make200Response()); originResponse.setHeader("Cache-Control", "max-age=3600"); originResponse.setHeader(header, value); backendExpectsAnyRequest().andReturn(originResponse); replayMocks(); impl.execute(route, req1, context, null); final HttpResponse result = impl.execute(route, req2, context, null); verifyMocks(); Assert.assertEquals(value, result.getFirstHeader(header).getValue()); }
@Test public void testResponseToA1_0RequestShouldUse1_1() throws Exception { request = HttpRequestWrapper.wrap( new BasicHttpRequest("GET", "/foo", new ProtocolVersion("HTTP", 1, 0))); 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); verifyMocks(); Assert.assertEquals(HttpVersion.HTTP_1_1, result.getProtocolVersion()); }
@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 testPreserveCustomProxyConnectionHeader() throws Exception { final HttpRequest request = new BasicHttpRequest("GET", "/"); request.addHeader("Proxy-Connection", HTTP.CONN_CLOSE); final HttpClientContext context = HttpClientContext.create(); final HttpHost target = new HttpHost("localhost", 80, "http"); final HttpHost proxy = new HttpHost("localhost", 8080); final HttpRoute route = new HttpRoute(target, null, proxy, false, TunnelType.PLAIN, LayerType.PLAIN); context.setAttribute(HttpClientContext.HTTP_ROUTE, route); final HttpRequestInterceptor interceptor = new RequestClientConnControl(); interceptor.process(request, context); final Header header1 = request.getFirstHeader("Proxy-Connection"); Assert.assertNotNull(header1); Assert.assertEquals(HTTP.CONN_CLOSE, header1.getValue()); }
@Test public void testNoCookieStore() throws Exception { final HttpRequest request = new BasicHttpRequest("GET", "/"); final HttpRoute route = new HttpRoute(this.target, null, false); final HttpClientContext context = HttpClientContext.create(); context.setAttribute(HttpCoreContext.HTTP_TARGET_HOST, this.target); context.setAttribute(HttpClientContext.HTTP_ROUTE, route); context.setAttribute(HttpClientContext.COOKIE_STORE, null); context.setAttribute(HttpClientContext.COOKIESPEC_REGISTRY, this.cookieSpecRegistry); final HttpRequestInterceptor interceptor = new RequestAddCookies(); interceptor.process(request, context); final Header[] headers1 = request.getHeaders(SM.COOKIE); Assert.assertNotNull(headers1); Assert.assertEquals(0, headers1.length); final Header[] headers2 = request.getHeaders(SM.COOKIE2); Assert.assertNotNull(headers2); Assert.assertEquals(0, headers2.length); }
@Test public void testAuthChallengeStateNoOption() throws Exception { final HttpRequest request = new BasicHttpRequest("GET", "/"); this.authState.setState(AuthProtocolState.CHALLENGED); this.authState.update(this.authScheme, this.credentials); Mockito.when(this.authScheme.authenticate( Mockito.any(Credentials.class), Mockito.any(HttpRequest.class), Mockito.any(HttpContext.class))).thenReturn(new BasicHeader(AUTH.WWW_AUTH_RESP, "stuff")); this.httpAuthenticator.generateAuthResponse(request, authState, context); Assert.assertTrue(request.containsHeader(AUTH.WWW_AUTH_RESP)); Mockito.verify(this.authScheme).authenticate(this.credentials, request, this.context); }
@Test public void testDefaultHeaders() throws Exception { final HttpRequest request = new BasicHttpRequest("GET", "/"); request.addHeader("custom", "stuff"); final List<Header> defheaders = new ArrayList<Header>(); defheaders.add(new BasicHeader("custom", "more stuff")); final HttpContext context = new BasicHttpContext(); final HttpRequestInterceptor interceptor = new RequestDefaultHeaders(defheaders); interceptor.process(request, context); final Header[] headers = request.getHeaders("custom"); Assert.assertNotNull(headers); Assert.assertEquals(2, headers.length); Assert.assertEquals("stuff", headers[0].getValue()); Assert.assertEquals("more stuff", headers[1].getValue()); }
protected void testGenerates504IfCannotRevalidateStaleResponse( final HttpResponse staleResponse) throws Exception { final HttpRequestWrapper req1 = HttpRequestWrapper.wrap( new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_1)); backendExpectsAnyRequestAndReturn(staleResponse); final HttpRequestWrapper req2 = HttpRequestWrapper.wrap( new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_1)); backendExpectsAnyRequest().andThrow(new SocketTimeoutException()); replayMocks(); impl.execute(route, req1, context, null); final HttpResponse result = impl.execute(route, req2, context, null); verifyMocks(); Assert.assertEquals(HttpStatus.SC_GATEWAY_TIMEOUT, result.getStatusLine().getStatusCode()); }
@Test public void testDigestAuthenticationWithSHA() throws Exception { final String challenge = "Digest realm=\"realm1\", " + "nonce=\"f2a3f18799759d4f1a1c068b92b573cb\", " + "algorithm=SHA"; final Header authChallenge = new BasicHeader(AUTH.WWW_AUTH, challenge); final HttpRequest request = new BasicHttpRequest("Simple", "/"); final Credentials cred = new UsernamePasswordCredentials("username","password"); final HttpContext context = new BasicHttpContext(); final DigestScheme authscheme = new DigestScheme(); authscheme.processChallenge(authChallenge); final Header authResponse = authscheme.authenticate(cred, request, context); final Map<String, String> table = parseAuthResponse(authResponse); Assert.assertEquals("username", table.get("username")); Assert.assertEquals("realm1", table.get("realm")); Assert.assertEquals("/", table.get("uri")); Assert.assertEquals("f2a3f18799759d4f1a1c068b92b573cb", table.get("nonce")); Assert.assertEquals("8769e82e4e28ecc040b969562b9050580c6d186d", table.get("response")); }
private void testDoesNotAddHeaderOnCacheHit(final String header) throws Exception { final HttpRequestWrapper req1 = HttpRequestWrapper.wrap( new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_1)); final HttpRequestWrapper req2 = HttpRequestWrapper.wrap( new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_1)); originResponse.addHeader("Cache-Control", "max-age=3600"); originResponse.removeHeaders(header); backendExpectsAnyRequest().andReturn(originResponse); replayMocks(); impl.execute(route, req1, context, null); final HttpResponse result = impl.execute(route, req2, context, null); verifyMocks(); Assert.assertNull(result.getFirstHeader(header)); }
@Test public void testResponsesToDELETEsAreNotCached() throws Exception { emptyMockCacheExpectsNoPuts(); request = HttpRequestWrapper.wrap(new BasicHttpRequest("DELETE", "/", HttpVersion.HTTP_1_1)); originResponse.setHeader("Cache-Control", "max-age=3600"); EasyMock.expect( mockBackend.execute( EasyMock.isA(HttpRoute.class), EasyMock.isA(HttpRequestWrapper.class), EasyMock.isA(HttpClientContext.class), EasyMock.<HttpExecutionAware>isNull())).andReturn(originResponse); replayMocks(); impl.execute(route, request, context, null); verifyMocks(); }
@Test public void testProxyConnectionKeepAliveForRequestsOverProxy() throws Exception { final HttpRequest request = new BasicHttpRequest("GET", "/"); final HttpClientContext context = HttpClientContext.create(); final HttpHost target = new HttpHost("localhost", 80, "http"); final HttpHost proxy = new HttpHost("localhost", 8080); final HttpRoute route = new HttpRoute(target, null, proxy, false, TunnelType.PLAIN, LayerType.PLAIN); context.setAttribute(HttpClientContext.HTTP_ROUTE, route); final HttpRequestInterceptor interceptor = new RequestClientConnControl(); interceptor.process(request, context); final Header header1 = request.getFirstHeader("Proxy-Connection"); Assert.assertNotNull(header1); Assert.assertEquals(HTTP.CONN_KEEP_ALIVE, header1.getValue()); final Header header2 = request.getFirstHeader(HTTP.CONN_DIRECTIVE); Assert.assertNull(header2); }
@Test public void testAuthDefaultHttpPortWhenProxy() throws Exception { final HttpRequest request = new BasicHttpRequest("GET", "/stuff"); this.target = new HttpHost("localhost.local"); final HttpRoute route = new HttpRoute( new HttpHost("localhost.local", 80), null, new HttpHost("localhost", 8888), false); final HttpClientContext context = HttpClientContext.create(); context.setAttribute(HttpCoreContext.HTTP_TARGET_HOST, this.target); context.setAttribute(HttpClientContext.HTTP_ROUTE, route); context.setAttribute(HttpClientContext.COOKIE_STORE, this.cookieStore); context.setAttribute(HttpClientContext.COOKIESPEC_REGISTRY, this.cookieSpecRegistry); final HttpRequestInterceptor interceptor = new RequestAddCookies(); interceptor.process(request, context); final CookieOrigin cookieOrigin = context.getCookieOrigin(); Assert.assertNotNull(cookieOrigin); Assert.assertEquals(this.target.getHostName(), cookieOrigin.getHost()); Assert.assertEquals(80, cookieOrigin.getPort()); Assert.assertEquals("/stuff", cookieOrigin.getPath()); Assert.assertFalse(cookieOrigin.isSecure()); }
@Test public void testResponsesToTRACEsAreNotCached() throws Exception { emptyMockCacheExpectsNoPuts(); request = HttpRequestWrapper.wrap(new BasicHttpRequest("TRACE", "/", HttpVersion.HTTP_1_1)); originResponse.setHeader("Cache-Control", "max-age=3600"); EasyMock.expect( mockBackend.execute( EasyMock.isA(HttpRoute.class), EasyMock.isA(HttpRequestWrapper.class), EasyMock.isA(HttpClientContext.class), EasyMock.<HttpExecutionAware>isNull())).andReturn(originResponse); replayMocks(); impl.execute(route, request, context, null); verifyMocks(); }
@Test public void testNoHttpConnection() throws Exception { final HttpRequest request = new BasicHttpRequest("GET", "/"); final HttpClientContext context = HttpClientContext.create(); context.setAttribute(HttpCoreContext.HTTP_TARGET_HOST, this.target); context.setAttribute(HttpCoreContext.HTTP_CONNECTION, null); context.setAttribute(HttpClientContext.COOKIE_STORE, this.cookieStore); context.setAttribute(HttpClientContext.COOKIESPEC_REGISTRY, this.cookieSpecRegistry); final HttpRequestInterceptor interceptor = new RequestAddCookies(); interceptor.process(request, context); final Header[] headers1 = request.getHeaders(SM.COOKIE); Assert.assertNotNull(headers1); Assert.assertEquals(0, headers1.length); final Header[] headers2 = request.getHeaders(SM.COOKIE2); Assert.assertNotNull(headers2); Assert.assertEquals(0, headers2.length); }
@Test public void testResponsesToOPTIONSAreNotCacheable() throws Exception { emptyMockCacheExpectsNoPuts(); request = HttpRequestWrapper.wrap(new BasicHttpRequest("OPTIONS", "/", HttpVersion.HTTP_1_1)); originResponse.addHeader("Cache-Control", "max-age=3600"); EasyMock.expect( mockBackend.execute( EasyMock.eq(route), EasyMock.isA(HttpRequestWrapper.class), 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)); }
public HttpResponse doGET(URI url) throws IOException, HttpException { String uri = url.getRawPath() + (url.getRawQuery() != null ? "?" + url.getRawQuery() : ""); HttpRequest request = new BasicHttpRequest("GET", uri); String hostHeader = (url.getPort() == 0 || url.getPort() == 80) ? url.getHost() : (url.getHost() + ":" + url.getPort()); request.addHeader("Host", hostHeader); return execute(request); }
/** * Creates the CONNECT request for tunnelling. * Called by {@link #createTunnelToTarget createTunnelToTarget}. * * @param route the route to establish * @param context the context for request execution * * @return the CONNECT request for tunnelling */ protected HttpRequest createConnectRequest(HttpRoute route, HttpContext context) { // see RFC 2817, section 5.2 and // INTERNET-DRAFT: Tunneling TCP based protocols through // Web proxy servers HttpHost target = route.getTargetHost(); String host = target.getHostName(); int port = target.getPort(); if (port < 0) { Scheme scheme = connManager.getSchemeRegistry(). getScheme(target.getSchemeName()); port = scheme.getDefaultPort(); } StringBuilder buffer = new StringBuilder(host.length() + 6); buffer.append(host); buffer.append(':'); buffer.append(Integer.toString(port)); String authority = buffer.toString(); ProtocolVersion ver = HttpProtocolParams.getVersion(params); HttpRequest req = new BasicHttpRequest ("CONNECT", authority, ver); return req; }
public HttpRequest newHttpRequest(final String method, final String uri) throws MethodNotSupportedException { if (isOneOf(RFC2616_COMMON_METHODS, method)) { return new BasicHttpRequest(method, uri); } else if (isOneOf(RFC2616_ENTITY_ENC_METHODS, method)) { return new BasicHttpEntityEnclosingRequest(method, uri); } else if (isOneOf(RFC2616_SPECIAL_METHODS, method)) { return new BasicHttpRequest(method, uri); } else { throw new MethodNotSupportedException(method + " method not supported"); } }
@Test public void testMultiHeadersAreSuccessfullyReplacedOn304Validation() throws Exception { final HttpRequestWrapper req1 = HttpRequestWrapper.wrap( new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_1)); final HttpResponse resp1 = HttpTestUtils.make200Response(); resp1.addHeader("Cache-Control","max-age=3600"); resp1.addHeader("Cache-Control","public"); resp1.setHeader("ETag","\"etag\""); final HttpRequestWrapper req2 = HttpRequestWrapper.wrap( new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_1)); req2.setHeader("Cache-Control", "max-age=0, max-stale=0"); final HttpResponse resp2 = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_NOT_MODIFIED, "Not Modified"); resp2.setHeader("Cache-Control", "max-age=1800"); backendExpectsAnyRequestAndReturn(resp1); backendExpectsAnyRequestAndReturn(resp2); final HttpRequestWrapper req3 = HttpRequestWrapper.wrap( new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_1)); replayMocks(); impl.execute(route, req1, context, null); final HttpResponse result1 = impl.execute(route, req2, context, null); final HttpResponse result2 = impl.execute(route, req3, context, null); verifyMocks(); final String h = "Cache-Control"; Assert.assertEquals(HttpTestUtils.getCanonicalHeaderValue(resp2, h), HttpTestUtils.getCanonicalHeaderValue(result1, h)); Assert.assertEquals(HttpTestUtils.getCanonicalHeaderValue(resp2, h), HttpTestUtils.getCanonicalHeaderValue(result2, h)); }
@Test public void testDoesNotInvalidateGETCacheEntryIfSubsequentGETRequestsAreMadeToTheSameURI() throws Exception { impl = new CacheInvalidator(cacheKeyGenerator, mockStorage); final String theURI = "http://foo.example.com:80/"; request = new BasicHttpRequest("GET", theURI,HTTP_1_1); cacheEntryisForMethod("GET"); cacheReturnsEntryForUri(theURI); impl.flushInvalidatedCacheEntries(host, request); verify(mockEntry).getRequestMethod(); verify(mockStorage).getEntry(theURI); verifyNoMoreInteractions(mockStorage); }
public HttpRequest newHttpRequest(final RequestLine requestline) throws MethodNotSupportedException { Args.notNull(requestline, "Request line"); final String method = requestline.getMethod(); if (isOneOf(RFC2616_COMMON_METHODS, method)) { return new BasicHttpRequest(requestline); } else if (isOneOf(RFC2616_ENTITY_ENC_METHODS, method)) { return new BasicHttpEntityEnclosingRequest(requestline); } else if (isOneOf(RFC2616_SPECIAL_METHODS, method)) { return new BasicHttpRequest(requestline); } else { throw new MethodNotSupportedException(method + " method not supported"); } }