List of usage examples for org.apache.http.protocol HttpCoreContext HTTP_TARGET_HOST
String HTTP_TARGET_HOST
To view the source code for org.apache.http.protocol HttpCoreContext HTTP_TARGET_HOST.
Click Source Link
From source file:cn.wanghaomiao.seimi.core.SeimiProcessor.java
private String getRealUrl(HttpContext httpContext) { Object target = httpContext.getAttribute(HttpCoreContext.HTTP_TARGET_HOST); Object reqUri = httpContext.getAttribute(HttpCoreContext.HTTP_REQUEST); if (target == null || reqUri == null) { return null; }/*from w w w . j av a 2 s. co m*/ HttpHost t = (HttpHost) target; HttpUriRequest r = (HttpUriRequest) reqUri; return r.getURI().isAbsolute() ? r.getURI().toString() : t.toString() + r.getURI().toString(); }
From source file:org.aludratest.service.gui.web.selenium.selenium2.AludraSeleniumHttpCommandExecutor.java
private URI buildUri(HttpContext context, String location) throws URISyntaxException { URI uri;//from w w w .j a v a 2 s . c om uri = new URI(location); if (!uri.isAbsolute()) { HttpHost host = (HttpHost) context.getAttribute(HttpCoreContext.HTTP_TARGET_HOST); uri = new URI(host.toURI() + location); } return uri; }
From source file:org.elasticsearch.xpack.security.authc.saml.SamlAuthenticationIT.java
/** * Navigates to the login page on the local (in memory) HTTP UI. * * @return A URI to which the "login form" should be submitted. *///from www . ja v a 2 s. co m private URI goToLoginPage(CloseableHttpClient client, BasicHttpContext context) throws IOException { HttpGet login = new HttpGet(getUrl(SP_LOGIN_PATH)); String target = execute(client, login, context, response -> { assertHttpOk(response.getStatusLine()); return getFormTarget(response.getEntity().getContent()); }); assertThat("Cannot find form target", target, Matchers.notNullValue()); assertThat("Target must be an absolute path", target, startsWith("/")); final Object host = context.getAttribute(HttpCoreContext.HTTP_TARGET_HOST); assertThat(host, instanceOf(HttpHost.class)); final String uri = ((HttpHost) host).toURI() + target; return toUri(uri); }
From source file:org.aludratest.service.gui.web.selenium.selenium2.AludraSeleniumHttpCommandExecutor.java
private Response createResponse(HttpResponse httpResponse, HttpContext context) throws IOException { org.openqa.selenium.remote.http.HttpResponse internalResponse = new org.openqa.selenium.remote.http.HttpResponse(); internalResponse.setStatus(httpResponse.getStatusLine().getStatusCode()); for (Header header : httpResponse.getAllHeaders()) { for (HeaderElement headerElement : header.getElements()) { internalResponse.addHeader(header.getName(), headerElement.getValue()); }//from w ww . j av a2s . c o m } HttpEntity entity = httpResponse.getEntity(); if (entity != null) { try { internalResponse.setContent(EntityUtils.toByteArray(entity)); } finally { EntityUtils.consume(entity); } } Response response = responseCodec.decode(internalResponse); if (response.getSessionId() == null) { HttpHost finalHost = (HttpHost) context.getAttribute(HttpCoreContext.HTTP_TARGET_HOST); String uri = finalHost.toURI(); String sessionId = HttpSessionId.getSessionId(uri); response.setSessionId(sessionId); } return response; }
From source file:com.googlecode.jdeltasync.DeltaSyncClient.java
private <T> T post(final IDeltaSyncSession session, String uri, final String userAgent, final String contentType, final byte[] data, final UriCapturingResponseHandler<T> handler) throws DeltaSyncException, IOException { final HttpPost post = createHttpPost(uri, userAgent, contentType, data); final HttpContext context = new BasicHttpContext(); context.setAttribute(HttpClientContext.COOKIE_STORE, session.getCookieStore()); try {//from w w w . j a v a 2s .c om return httpClient.execute(post, new ResponseHandler<T>() { public T handleResponse(HttpResponse response) throws ClientProtocolException, IOException { try { if (isRedirect(response)) { URI redirectUri = getRedirectLocationURI(session, post, response, context); return post(session, redirectUri.toString(), userAgent, contentType, data, handler); } if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) { throw new HttpException(response.getStatusLine().getStatusCode(), response.getStatusLine().getReasonPhrase()); } HttpRequest request = (HttpRequest) context.getAttribute(HttpCoreContext.HTTP_REQUEST); HttpHost host = (HttpHost) context.getAttribute(HttpCoreContext.HTTP_TARGET_HOST); URI uri; try { if (request instanceof HttpUriRequest) { uri = ((HttpUriRequest) request).getURI(); } else { uri = new URI(request.getRequestLine().getUri()); } if (!uri.isAbsolute()) { uri = URIUtils.rewriteURI(uri, host); } } catch (URISyntaxException e) { throw new DeltaSyncException(e); } return handler.handle(uri, response); } catch (DeltaSyncException e) { throw new RuntimeException(e); } } }, context); } catch (RuntimeException e) { Throwable t = e.getCause(); while (t != null) { if (t instanceof DeltaSyncException) { throw (DeltaSyncException) t; } t = t.getCause(); } throw e; } }
From source file:crawlercommons.fetcher.http.SimpleHttpFetcher.java
private String extractRedirectedUrl(String url, HttpContext localContext) { // This was triggered by HttpClient with the redirect count was // exceeded.//from w w w . j a va 2 s .com HttpHost host = (HttpHost) localContext.getAttribute(HttpCoreContext.HTTP_TARGET_HOST); HttpUriRequest finalRequest = (HttpUriRequest) localContext.getAttribute(HttpCoreContext.HTTP_REQUEST); try { URL hostUrl = new URI(host.toURI()).toURL(); return new URL(hostUrl, finalRequest.getURI().toString()).toExternalForm(); } catch (MalformedURLException e) { LOGGER.warn("Invalid host/uri specified in final fetch: " + host + finalRequest.getURI()); return url; } catch (URISyntaxException e) { LOGGER.warn("Invalid host/uri specified in final fetch: " + host + finalRequest.getURI()); return url; } }
From source file:org.apache.http.impl.client.cache.CachingHttpAsyncClient.java
private void handleCacheHit(final BasicFuture<HttpResponse> future, final HttpHost target, final HttpRequestWrapper request, final HttpCacheContext clientContext, final HttpCacheEntry entry) throws IOException { recordCacheHit(target, request);//from w ww . j a v a2s . co m final HttpResponse out; final Date now = getCurrentDate(); if (this.suitabilityChecker.canCachedResponseBeUsed(target, request, entry, now)) { log.debug("Cache hit"); out = generateCachedResponse(request, clientContext, entry, now); } else if (!mayCallBackend(request)) { log.debug("Cache entry not suitable but only-if-cached requested"); out = generateGatewayTimeout(clientContext); } else if (validityPolicy.isRevalidatable(entry) && !(entry.getStatusCode() == HttpStatus.SC_NOT_MODIFIED && !suitabilityChecker.isConditional(request))) { log.debug("Revalidating cache entry"); revalidateCacheEntry(future, target, request, clientContext, entry, now); return; } else { log.debug("Cache entry not usable; calling backend"); callBackend(future, target, request, clientContext); return; } clientContext.setAttribute(HttpClientContext.HTTP_ROUTE, new HttpRoute(target)); clientContext.setAttribute(HttpCoreContext.HTTP_TARGET_HOST, target); clientContext.setAttribute(HttpCoreContext.HTTP_REQUEST, request); clientContext.setAttribute(HttpCoreContext.HTTP_RESPONSE, out); clientContext.setAttribute(HttpCoreContext.HTTP_REQ_SENT, Boolean.TRUE); future.completed(out); }
From source file:org.apache.http.impl.execchain.MinimalClientExec.java
public CloseableHttpResponse execute(final HttpRoute route, final HttpRequestWrapper request, final HttpClientContext context, final HttpExecutionAware execAware) throws IOException, HttpException { Args.notNull(route, "HTTP route"); Args.notNull(request, "HTTP request"); Args.notNull(context, "HTTP context"); rewriteRequestURI(request, route);/*from w ww . j a v a 2 s . co m*/ final ConnectionRequest connRequest = connManager.requestConnection(route, null); if (execAware != null) { if (execAware.isAborted()) { connRequest.cancel(); throw new RequestAbortedException("Request aborted"); } else { execAware.setCancellable(connRequest); } } final RequestConfig config = context.getRequestConfig(); final HttpClientConnection managedConn; try { final int timeout = config.getConnectionRequestTimeout(); managedConn = connRequest.get(timeout > 0 ? timeout : 0, TimeUnit.MILLISECONDS); } catch (final InterruptedException interrupted) { Thread.currentThread().interrupt(); throw new RequestAbortedException("Request aborted", interrupted); } catch (final ExecutionException ex) { Throwable cause = ex.getCause(); if (cause == null) { cause = ex; } throw new RequestAbortedException("Request execution failed", cause); } final ConnectionHolder releaseTrigger = new ConnectionHolder(log, connManager, managedConn); try { if (execAware != null) { if (execAware.isAborted()) { releaseTrigger.close(); throw new RequestAbortedException("Request aborted"); } else { execAware.setCancellable(releaseTrigger); } } if (!managedConn.isOpen()) { final int timeout = config.getConnectTimeout(); this.connManager.connect(managedConn, route, timeout > 0 ? timeout : 0, context); this.connManager.routeComplete(managedConn, route, context); } final int timeout = config.getSocketTimeout(); if (timeout >= 0) { managedConn.setSocketTimeout(timeout); } HttpHost target = null; final HttpRequest original = request.getOriginal(); if (original instanceof HttpUriRequest) { final URI uri = ((HttpUriRequest) original).getURI(); if (uri.isAbsolute()) { target = new HttpHost(uri.getHost(), uri.getPort(), uri.getScheme()); } } if (target == null) { target = route.getTargetHost(); } context.setAttribute(HttpCoreContext.HTTP_TARGET_HOST, target); context.setAttribute(HttpCoreContext.HTTP_REQUEST, request); context.setAttribute(HttpCoreContext.HTTP_CONNECTION, managedConn); context.setAttribute(HttpClientContext.HTTP_ROUTE, route); httpProcessor.process(request, context); final HttpResponse response = requestExecutor.execute(request, managedConn, context); httpProcessor.process(response, context); // The connection is in or can be brought to a re-usable state. if (reuseStrategy.keepAlive(response, context)) { // Set the idle duration of this connection final long duration = keepAliveStrategy.getKeepAliveDuration(response, context); releaseTrigger.setValidFor(duration, TimeUnit.MILLISECONDS); releaseTrigger.markReusable(); } else { releaseTrigger.markNonReusable(); } // check for entity, release connection if possible final HttpEntity entity = response.getEntity(); if (entity == null || !entity.isStreaming()) { // connection not needed and (assumed to be) in re-usable state releaseTrigger.releaseConnection(); return Proxies.enhanceResponse(response, null); } else { return Proxies.enhanceResponse(response, releaseTrigger); } } catch (final ConnectionShutdownException ex) { final InterruptedIOException ioex = new InterruptedIOException("Connection has been shut down"); ioex.initCause(ex); throw ioex; } catch (final HttpException ex) { releaseTrigger.abortConnection(); throw ex; } catch (final IOException ex) { releaseTrigger.abortConnection(); throw ex; } catch (final RuntimeException ex) { releaseTrigger.abortConnection(); throw ex; } }
From source file:org.apache.http.impl.execchain.ProtocolExec.java
public CloseableHttpResponse execute(final HttpRoute route, final HttpRequestWrapper request, final HttpClientContext context, final HttpExecutionAware execAware) throws IOException, HttpException { Args.notNull(route, "HTTP route"); Args.notNull(request, "HTTP request"); Args.notNull(context, "HTTP context"); final HttpRequest original = request.getOriginal(); URI uri = null;// www. j a v a2 s . co m if (original instanceof HttpUriRequest) { uri = ((HttpUriRequest) original).getURI(); } else { final String uriString = original.getRequestLine().getUri(); try { uri = URI.create(uriString); } catch (final IllegalArgumentException ex) { if (this.log.isDebugEnabled()) { this.log.debug("Unable to parse '" + uriString + "' as a valid URI; " + "request URI and Host header may be inconsistent", ex); } } } request.setURI(uri); // Re-write request URI if needed rewriteRequestURI(request, route); final HttpParams params = request.getParams(); HttpHost virtualHost = (HttpHost) params.getParameter(ClientPNames.VIRTUAL_HOST); // HTTPCLIENT-1092 - add the port if necessary if (virtualHost != null && virtualHost.getPort() == -1) { final int port = route.getTargetHost().getPort(); if (port != -1) { virtualHost = new HttpHost(virtualHost.getHostName(), port, virtualHost.getSchemeName()); } if (this.log.isDebugEnabled()) { this.log.debug("Using virtual host" + virtualHost); } } HttpHost target = null; if (virtualHost != null) { target = virtualHost; } else { if (uri != null && uri.isAbsolute() && uri.getHost() != null) { target = new HttpHost(uri.getHost(), uri.getPort(), uri.getScheme()); } } if (target == null) { target = route.getTargetHost(); } // Get user info from the URI if (uri != null) { final String userinfo = uri.getUserInfo(); if (userinfo != null) { CredentialsProvider credsProvider = context.getCredentialsProvider(); if (credsProvider == null) { credsProvider = new BasicCredentialsProvider(); context.setCredentialsProvider(credsProvider); } credsProvider.setCredentials(new AuthScope(target), new UsernamePasswordCredentials(userinfo)); } } // Run request protocol interceptors context.setAttribute(HttpCoreContext.HTTP_TARGET_HOST, target); context.setAttribute(HttpClientContext.HTTP_ROUTE, route); context.setAttribute(HttpCoreContext.HTTP_REQUEST, request); this.httpProcessor.process(request, context); final CloseableHttpResponse response = this.requestExecutor.execute(route, request, context, execAware); try { // Run response protocol interceptors context.setAttribute(HttpCoreContext.HTTP_RESPONSE, response); this.httpProcessor.process(response, context); return response; } catch (final RuntimeException ex) { response.close(); throw ex; } catch (final IOException ex) { response.close(); throw ex; } catch (final HttpException ex) { response.close(); throw ex; } }