List of usage examples for org.apache.http.protocol ExecutionContext HTTP_TARGET_HOST
String HTTP_TARGET_HOST
To view the source code for org.apache.http.protocol ExecutionContext HTTP_TARGET_HOST.
Click Source Link
From source file:com.amytech.android.library.utils.asynchttp.AsyncHttpClient.java
/** * Creates a new AsyncHttpClient.//from ww w.ja va 2 s . c o m * * @param schemeRegistry * SchemeRegistry to be used */ public AsyncHttpClient(SchemeRegistry schemeRegistry) { BasicHttpParams httpParams = new BasicHttpParams(); ConnManagerParams.setTimeout(httpParams, connectTimeout); ConnManagerParams.setMaxConnectionsPerRoute(httpParams, new ConnPerRouteBean(maxConnections)); ConnManagerParams.setMaxTotalConnections(httpParams, DEFAULT_MAX_CONNECTIONS); HttpConnectionParams.setSoTimeout(httpParams, responseTimeout); HttpConnectionParams.setConnectionTimeout(httpParams, connectTimeout); HttpConnectionParams.setTcpNoDelay(httpParams, true); HttpConnectionParams.setSocketBufferSize(httpParams, DEFAULT_SOCKET_BUFFER_SIZE); HttpProtocolParams.setVersion(httpParams, HttpVersion.HTTP_1_1); ClientConnectionManager cm = createConnectionManager(schemeRegistry, httpParams); Utils.asserts(cm != null, "Custom implementation of #createConnectionManager(SchemeRegistry, BasicHttpParams) returned null"); threadPool = getDefaultThreadPool(); requestMap = Collections.synchronizedMap(new WeakHashMap<Context, List<RequestHandle>>()); clientHeaderMap = new HashMap<String, String>(); httpContext = new SyncBasicHttpContext(new BasicHttpContext()); httpClient = new DefaultHttpClient(cm, httpParams); httpClient.addRequestInterceptor(new HttpRequestInterceptor() { @Override public void process(HttpRequest request, HttpContext context) { if (!request.containsHeader(HEADER_ACCEPT_ENCODING)) { request.addHeader(HEADER_ACCEPT_ENCODING, ENCODING_GZIP); } for (String header : clientHeaderMap.keySet()) { if (request.containsHeader(header)) { Header overwritten = request.getFirstHeader(header); Log.d(LOG_TAG, String.format("Headers were overwritten! (%s | %s) overwrites (%s | %s)", header, clientHeaderMap.get(header), overwritten.getName(), overwritten.getValue())); // remove the overwritten header request.removeHeader(overwritten); } request.addHeader(header, clientHeaderMap.get(header)); } } }); httpClient.addResponseInterceptor(new HttpResponseInterceptor() { @Override public void process(HttpResponse response, HttpContext context) { final HttpEntity entity = response.getEntity(); if (entity == null) { return; } final Header encoding = entity.getContentEncoding(); if (encoding != null) { for (HeaderElement element : encoding.getElements()) { if (element.getName().equalsIgnoreCase(ENCODING_GZIP)) { response.setEntity(new InflatingEntity(entity)); break; } } } } }); httpClient.addRequestInterceptor(new HttpRequestInterceptor() { @Override public void process(final HttpRequest request, final HttpContext context) throws HttpException, IOException { AuthState authState = (AuthState) context.getAttribute(ClientContext.TARGET_AUTH_STATE); CredentialsProvider credsProvider = (CredentialsProvider) context .getAttribute(ClientContext.CREDS_PROVIDER); HttpHost targetHost = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST); if (authState.getAuthScheme() == null) { AuthScope authScope = new AuthScope(targetHost.getHostName(), targetHost.getPort()); Credentials creds = credsProvider.getCredentials(authScope); if (creds != null) { authState.setAuthScheme(new BasicScheme()); authState.setCredentials(creds); } } } }, 0); httpClient .setHttpRequestRetryHandler(new RetryHandler(DEFAULT_MAX_RETRIES, DEFAULT_RETRY_SLEEP_TIME_MILLIS)); }
From source file:org.ellis.yun.search.test.httpclient.HttpClientTest.java
/** * HTTPHttpClient<br>/*from w w w . j a v a 2s. c o m*/ * 'http.connection'HttpConnection? ? * 'http.target_host'HttpHost ? * 'http.proxy_host'HttpHost? ? * 'http.request'HttpRequestHTTP ? * 'http.response'HttpResponseHTTP? ? * 'http.request_sent'java.lang.Boolean?? * * @throws Exception */ @Test @SuppressWarnings("deprecation") public void testHttpContext() throws Exception { DefaultHttpClient httpclient = new DefaultHttpClient(); // httpContext ?httpClienthttp? HttpContext httpContext = new BasicHttpContext(); HttpGet httpGet = new HttpGet(URL1); HttpResponse response = httpclient.execute(httpGet, httpContext); ManagedClientConnection connection = (ManagedClientConnection) httpContext .getAttribute(ExecutionContext.HTTP_CONNECTION); System.out.println("LocalAddr ==> " + connection.getLocalAddress().getHostAddress()); System.out.println("LocalPort ==> " + connection.getLocalPort()); System.out.println("RemoteAddr ==> " + connection.getRemoteAddress().getHostAddress()); System.out.println("RemotePort ==> " + connection.getRemotePort()); System.out.println("isOpen ==> " + connection.isOpen()); System.out.println("isSecure ==> " + connection.isSecure()); System.out.println("isStale ==> " + connection.isStale()); HttpHost targetHost = (HttpHost) httpContext.getAttribute(ExecutionContext.HTTP_TARGET_HOST); System.out.println(targetHost.toURI()); // HttpHost proxyHost = (HttpHost) httpContext // .getAttribute(ExecutionContext.HTTP_PROXY_HOST); // ?? HttpEntity entity = response.getEntity(); if (entity != null) { String content = parseEntity(entity); System.out.println(content); // ? entity.consumeContent(); } connection.abortConnection(); connection.shutdown(); }
From source file:derson.com.httpsender.AsyncHttpClient.AsyncHttpClient.java
/** * Creates a new AsyncHttpClient./* ww w . java 2 s . c o m*/ * * @param schemeRegistry SchemeRegistry to be used */ public AsyncHttpClient(SchemeRegistry schemeRegistry) { BasicHttpParams httpParams = new BasicHttpParams(); ConnManagerParams.setTimeout(httpParams, connectTimeout); ConnManagerParams.setMaxConnectionsPerRoute(httpParams, new ConnPerRouteBean(maxConnections)); ConnManagerParams.setMaxTotalConnections(httpParams, DEFAULT_MAX_CONNECTIONS); HttpConnectionParams.setSoTimeout(httpParams, responseTimeout); HttpConnectionParams.setConnectionTimeout(httpParams, connectTimeout); HttpConnectionParams.setTcpNoDelay(httpParams, true); HttpConnectionParams.setSocketBufferSize(httpParams, DEFAULT_SOCKET_BUFFER_SIZE); HttpProtocolParams.setVersion(httpParams, HttpVersion.HTTP_1_1); ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager(httpParams, schemeRegistry); threadPool = getDefaultThreadPool(); requestMap = Collections.synchronizedMap(new WeakHashMap<Context, List<RequestHandle>>()); clientHeaderMap = new HashMap<String, String>(); httpContext = new SyncBasicHttpContext(new BasicHttpContext()); httpClient = new DefaultHttpClient(cm, httpParams); httpClient.addRequestInterceptor(new HttpRequestInterceptor() { @Override public void process(HttpRequest request, HttpContext context) { if (!request.containsHeader(HEADER_ACCEPT_ENCODING)) { request.addHeader(HEADER_ACCEPT_ENCODING, ENCODING_GZIP); } for (String header : clientHeaderMap.keySet()) { if (request.containsHeader(header)) { Header overwritten = request.getFirstHeader(header); HPLog.d(LOG_TAG, String.format("Headers were overwritten! (%s | %s) overwrites (%s | %s)", header, clientHeaderMap.get(header), overwritten.getName(), overwritten.getValue())); //remove the overwritten header request.removeHeader(overwritten); } request.addHeader(header, clientHeaderMap.get(header)); } } }); httpClient.addResponseInterceptor(new HttpResponseInterceptor() { @Override public void process(HttpResponse response, HttpContext context) { final HttpEntity entity = response.getEntity(); if (entity == null) { return; } final Header encoding = entity.getContentEncoding(); if (encoding != null) { for (HeaderElement element : encoding.getElements()) { if (element.getName().equalsIgnoreCase(ENCODING_GZIP)) { response.setEntity(new InflatingEntity(entity)); break; } } } } }); httpClient.addRequestInterceptor(new HttpRequestInterceptor() { @Override public void process(final HttpRequest request, final HttpContext context) throws HttpException, IOException { AuthState authState = (AuthState) context.getAttribute(ClientContext.TARGET_AUTH_STATE); CredentialsProvider credsProvider = (CredentialsProvider) context .getAttribute(ClientContext.CREDS_PROVIDER); HttpHost targetHost = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST); if (authState.getAuthScheme() == null) { AuthScope authScope = new AuthScope(targetHost.getHostName(), targetHost.getPort()); Credentials creds = credsProvider.getCredentials(authScope); if (creds != null) { authState.setAuthScheme(new BasicScheme()); authState.setCredentials(creds); } } } }, 0); httpClient .setHttpRequestRetryHandler(new RetryHandler(DEFAULT_MAX_RETRIES, DEFAULT_RETRY_SLEEP_TIME_MILLIS)); }
From source file:org.apache.taverna.activities.rest.HTTPRequestHandler.java
/** * TODO - REDIRECTION output:: if there was no redirection, should just show * the actual initial URL?//from w w w .j ava2s . co m * * @param httpRequest * @param acceptHeaderValue */ private static HTTPRequestResponse performHTTPRequest(ClientConnectionManager connectionManager, HttpRequestBase httpRequest, RESTActivityConfigurationBean configBean, Map<String, String> urlParameters, CredentialsProvider credentialsProvider) { // headers are set identically for all HTTP methods, therefore can do // centrally - here // If the user wants to set MIME type for the 'Accepts' header String acceptsHeaderValue = configBean.getAcceptsHeaderValue(); if ((acceptsHeaderValue != null) && !acceptsHeaderValue.isEmpty()) { httpRequest.setHeader(ACCEPT_HEADER_NAME, URISignatureHandler.generateCompleteURI(acceptsHeaderValue, urlParameters, configBean.getEscapeParameters())); } // See if user wanted to set any other HTTP headers ArrayList<ArrayList<String>> otherHTTPHeaders = configBean.getOtherHTTPHeaders(); if (!otherHTTPHeaders.isEmpty()) for (ArrayList<String> httpHeaderNameValuePair : otherHTTPHeaders) if (httpHeaderNameValuePair.get(0) != null && !httpHeaderNameValuePair.get(0).isEmpty()) { String headerParameterizedValue = httpHeaderNameValuePair.get(1); String headerValue = URISignatureHandler.generateCompleteURI(headerParameterizedValue, urlParameters, configBean.getEscapeParameters()); httpRequest.setHeader(httpHeaderNameValuePair.get(0), headerValue); } try { HTTPRequestResponse requestResponse = new HTTPRequestResponse(); DefaultHttpClient httpClient = new DefaultHttpClient(connectionManager, null); ((DefaultHttpClient) httpClient).setCredentialsProvider(credentialsProvider); HttpContext localContext = new BasicHttpContext(); // Set the proxy settings, if any if (System.getProperty(PROXY_HOST) != null && !System.getProperty(PROXY_HOST).isEmpty()) { // Instruct HttpClient to use the standard // JRE proxy selector to obtain proxy information ProxySelectorRoutePlanner routePlanner = new ProxySelectorRoutePlanner( httpClient.getConnectionManager().getSchemeRegistry(), ProxySelector.getDefault()); httpClient.setRoutePlanner(routePlanner); // Do we need to authenticate the user to the proxy? if (System.getProperty(PROXY_USERNAME) != null && !System.getProperty(PROXY_USERNAME).isEmpty()) // Add the proxy username and password to the list of // credentials httpClient.getCredentialsProvider().setCredentials( new AuthScope(System.getProperty(PROXY_HOST), Integer.parseInt(System.getProperty(PROXY_PORT))), new UsernamePasswordCredentials(System.getProperty(PROXY_USERNAME), System.getProperty(PROXY_PASSWORD))); } // execute the request HttpResponse response = httpClient.execute(httpRequest, localContext); // record response code requestResponse.setStatusCode(response.getStatusLine().getStatusCode()); requestResponse.setReasonPhrase(response.getStatusLine().getReasonPhrase()); // record header values for Content-Type of the response requestResponse.setResponseContentTypes(response.getHeaders(CONTENT_TYPE_HEADER_NAME)); // track where did the final redirect go to (if there was any) HttpHost targetHost = (HttpHost) localContext.getAttribute(ExecutionContext.HTTP_TARGET_HOST); HttpUriRequest targetRequest = (HttpUriRequest) localContext .getAttribute(ExecutionContext.HTTP_REQUEST); requestResponse.setRedirectionURL("" + targetHost + targetRequest.getURI()); requestResponse.setRedirectionHTTPMethod(targetRequest.getMethod()); requestResponse.setHeaders(response.getAllHeaders()); /* read and store response body (check there is some content - negative length of content means unknown length; zero definitely means no content...)*/ // TODO - make sure that this test is sufficient to determine if // there is no response entity if (response.getEntity() != null && response.getEntity().getContentLength() != 0) requestResponse.setResponseBody(readResponseBody(response.getEntity())); // release resources (e.g. connection pool, etc) httpClient.getConnectionManager().shutdown(); return requestResponse; } catch (Exception ex) { return new HTTPRequestResponse(ex); } }
From source file:eu.thecoder4.gpl.pleftdroid.PleftBroker.java
/** * @return Returns SC_CLIREDIR if the client is being redirected (eg. for net authentication) * or SC_NOTPLEFTSERV if the server is not Pleft Server * or HttpStatus.SC_OK if everything is OK *///from www.j a v a 2 s.com protected static int checkServer(String pserver) { DefaultHttpClient client = getDefaultClient(); HttpContext context = new BasicHttpContext(); //We request the index HttpGet request = new HttpGet(pserver); HttpResponse response = null; try { response = client.execute(request, context); int SC = response.getStatusLine().getStatusCode(); Log.i("PB", "checkServ SC:" + SC); } catch (Exception e) { return SC_TIMEOUT; } HttpHost currentHost = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST); String host = currentHost.getHostName(); Log.i("PB", "checkServ finalhost=" + host + "==" + getHostName(pserver) + "=pserverhost ? " + host.equals(getHostName(pserver))); if (!host.equals(getHostName(pserver))) { try { response.getEntity().getContent().close(); //You need to open and close the IS to release the connection !!! } catch (Exception e) { } return SC_CLIREDIR; } //InputStream is; try { String html = EntityUtils.toString(response.getEntity()); //It consumes content ! if (html.contains("Pleft")) { return HttpStatus.SC_OK; } else { Log.i("PB", "checkServ NOPLEFT!"); return SC_NOTPLEFTSERV; } } catch (Exception e) { Log.i("PB", "checkServ Got exception2:" + e); return SC_NOTPLEFTSERV; } }
From source file:czd.lib.network.AsyncHttpClient.java
/** * Simple interface method, to enable or disable redirects. If you set manually RedirectHandler * on underlying HttpClient, effects of this method will be canceled. * * @param enableRedirects boolean//from w w w .java 2 s . c o m */ public void setEnableRedirects(final boolean enableRedirects) { if (enableRedirects) { httpClient.setRedirectHandler(new DefaultRedirectHandler() { @Override public boolean isRedirectRequested(HttpResponse response, HttpContext context) { if (response == null) { throw new IllegalArgumentException("HTTP response may not be null"); } int statusCode = response.getStatusLine().getStatusCode(); switch (statusCode) { case HttpStatus.SC_MOVED_TEMPORARILY: case HttpStatus.SC_MOVED_PERMANENTLY: case HttpStatus.SC_SEE_OTHER: case HttpStatus.SC_TEMPORARY_REDIRECT: return true; default: return false; } } @Override public URI getLocationURI(HttpResponse response, HttpContext context) throws ProtocolException { if (response == null) { throw new IllegalArgumentException("HTTP response may not be null"); } //get the location header to find out where to redirect to Header locationHeader = response.getFirstHeader("location"); if (locationHeader == null) { // got a redirect response, but no location header throw new ProtocolException("Received redirect response " + response.getStatusLine() + " but no location header"); } //HERE IS THE MODIFIED LINE OF CODE String location = locationHeader.getValue().replaceAll(" ", "%20"); URI uri; try { uri = new URI(location); } catch (URISyntaxException ex) { throw new ProtocolException("Invalid redirect URI: " + location, ex); } HttpParams params = response.getParams(); // rfc2616 demands the location value be a complete URI // Location = "Location" ":" absoluteURI if (!uri.isAbsolute()) { if (params.isParameterTrue(ClientPNames.REJECT_RELATIVE_REDIRECT)) { throw new ProtocolException("Relative redirect location '" + uri + "' not allowed"); } // Adjust location URI HttpHost target = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST); if (target == null) { throw new IllegalStateException("Target host not available " + "in the HTTP context"); } HttpRequest request = (HttpRequest) context.getAttribute(ExecutionContext.HTTP_REQUEST); try { URI requestURI = new URI(request.getRequestLine().getUri()); URI absoluteRequestURI = URIUtils.rewriteURI(requestURI, target, true); uri = URIUtils.resolve(absoluteRequestURI, uri); } catch (URISyntaxException ex) { throw new ProtocolException(ex.getMessage(), ex); } } if (params.isParameterFalse(ClientPNames.ALLOW_CIRCULAR_REDIRECTS)) { RedirectLocations redirectLocations = (RedirectLocations) context .getAttribute("http.protocol.redirect-locations"); if (redirectLocations == null) { redirectLocations = new RedirectLocations(); context.setAttribute("http.protocol.redirect-locations", redirectLocations); } URI redirectURI; if (uri.getFragment() != null) { try { HttpHost target = new HttpHost(uri.getHost(), uri.getPort(), uri.getScheme()); redirectURI = URIUtils.rewriteURI(uri, target, true); } catch (URISyntaxException ex) { throw new ProtocolException(ex.getMessage(), ex); } } else { redirectURI = uri; } if (redirectLocations.contains(redirectURI)) { throw new CircularRedirectException("Circular redirect to '" + redirectURI + "'"); } else { redirectLocations.add(redirectURI); } } return uri; } }); } }
From source file:org.opendatakit.dwc.server.GreetingServiceImpl.java
private static HttpRequestInterceptor getPreemptiveAuth() { return new HttpRequestInterceptor() { public void process(final HttpRequest request, final HttpContext context) throws HttpException, IOException { AuthState authState = (AuthState) context.getAttribute(ClientContext.TARGET_AUTH_STATE); CredentialsProvider credsProvider = (CredentialsProvider) context .getAttribute(ClientContext.CREDS_PROVIDER); HttpHost targetHost = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST); if (authState.getAuthScheme() == null) { AuthScope authScope = new AuthScope(targetHost.getHostName(), targetHost.getPort()); Credentials creds = credsProvider.getCredentials(authScope); if (creds != null) { authState.setAuthScheme(new BasicScheme()); authState.setCredentials(creds); }/*from ww w . jav a 2 s . c om*/ } } }; }
From source file:com.xtremelabs.robolectric.tester.org.apache.http.impl.client.DefaultRequestDirector.java
public HttpResponse execute(HttpHost target, HttpRequest request, HttpContext context) throws HttpException, IOException { HttpRequest orig = request;//from w ww . ja v a 2 s . c o m RequestWrapper origWrapper = wrapRequest(orig); origWrapper.setParams(params); HttpRoute origRoute = determineRoute(target, origWrapper, context); virtualHost = (HttpHost) orig.getParams().getParameter(ClientPNames.VIRTUAL_HOST); RoutedRequest roureq = new RoutedRequest(origWrapper, origRoute); long timeout = ConnManagerParams.getTimeout(params); int execCount = 0; boolean reuse = false; boolean done = false; try { HttpResponse response = null; while (!done) { // In this loop, the RoutedRequest may be replaced by a // followup request and route. The request and route passed // in the method arguments will be replaced. The original // request is still available in 'orig'. RequestWrapper wrapper = roureq.getRequest(); HttpRoute route = roureq.getRoute(); response = null; // See if we have a user token bound to the execution context Object userToken = context.getAttribute(ClientContext.USER_TOKEN); // Allocate connection if needed if (managedConn == null) { ClientConnectionRequest connRequest = connManager.requestConnection(route, userToken); if (orig instanceof AbortableHttpRequest) { ((AbortableHttpRequest) orig).setConnectionRequest(connRequest); } try { managedConn = connRequest.getConnection(timeout, TimeUnit.MILLISECONDS); } catch (InterruptedException interrupted) { InterruptedIOException iox = new InterruptedIOException(); iox.initCause(interrupted); throw iox; } if (HttpConnectionParams.isStaleCheckingEnabled(params)) { // validate connection if (managedConn.isOpen()) { this.log.debug("Stale connection check"); if (managedConn.isStale()) { this.log.debug("Stale connection detected"); managedConn.close(); } } } } if (orig instanceof AbortableHttpRequest) { ((AbortableHttpRequest) orig).setReleaseTrigger(managedConn); } // Reopen connection if needed if (!managedConn.isOpen()) { managedConn.open(route, context, params); } else { managedConn.setSocketTimeout(HttpConnectionParams.getSoTimeout(params)); } try { establishRoute(route, context); } catch (TunnelRefusedException ex) { if (this.log.isDebugEnabled()) { this.log.debug(ex.getMessage()); } response = ex.getResponse(); break; } // Reset headers on the request wrapper wrapper.resetHeaders(); // Re-write request URI if needed rewriteRequestURI(wrapper, route); // Use virtual host if set target = virtualHost; if (target == null) { target = route.getTargetHost(); } HttpHost proxy = route.getProxyHost(); // Populate the execution context context.setAttribute(ExecutionContext.HTTP_TARGET_HOST, target); context.setAttribute(ExecutionContext.HTTP_PROXY_HOST, proxy); context.setAttribute(ExecutionContext.HTTP_CONNECTION, managedConn); context.setAttribute(ClientContext.TARGET_AUTH_STATE, targetAuthState); context.setAttribute(ClientContext.PROXY_AUTH_STATE, proxyAuthState); // Run request protocol interceptors requestExec.preProcess(wrapper, httpProcessor, context); boolean retrying = true; Exception retryReason = null; while (retrying) { // Increment total exec count (with redirects) execCount++; // Increment exec count for this particular request wrapper.incrementExecCount(); if (!wrapper.isRepeatable()) { this.log.debug("Cannot retry non-repeatable request"); if (retryReason != null) { throw new NonRepeatableRequestException("Cannot retry request " + "with a non-repeatable request entity. The cause lists the " + "reason the original request failed: " + retryReason); } else { throw new NonRepeatableRequestException( "Cannot retry request " + "with a non-repeatable request entity."); } } try { if (this.log.isDebugEnabled()) { this.log.debug("Attempt " + execCount + " to execute request"); } response = requestExec.execute(wrapper, managedConn, context); retrying = false; } catch (IOException ex) { this.log.debug("Closing the connection."); managedConn.close(); if (retryHandler.retryRequest(ex, wrapper.getExecCount(), context)) { if (this.log.isInfoEnabled()) { this.log.info("I/O exception (" + ex.getClass().getName() + ") caught when processing request: " + ex.getMessage()); } if (this.log.isDebugEnabled()) { this.log.debug(ex.getMessage(), ex); } this.log.info("Retrying request"); retryReason = ex; } else { throw ex; } // If we have a direct route to the target host // just re-open connection and re-try the request if (!route.isTunnelled()) { this.log.debug("Reopening the direct connection."); managedConn.open(route, context, params); } else { // otherwise give up this.log.debug("Proxied connection. Need to start over."); retrying = false; } } } if (response == null) { // Need to start over continue; } // Run response protocol interceptors response.setParams(params); requestExec.postProcess(response, httpProcessor, context); // The connection is in or can be brought to a re-usable state. reuse = reuseStrategy.keepAlive(response, context); if (reuse) { // Set the idle duration of this connection long duration = keepAliveStrategy.getKeepAliveDuration(response, context); managedConn.setIdleDuration(duration, TimeUnit.MILLISECONDS); if (this.log.isDebugEnabled()) { if (duration >= 0) { this.log.debug("Connection can be kept alive for " + duration + " ms"); } else { this.log.debug("Connection can be kept alive indefinitely"); } } } RoutedRequest followup = handleResponse(roureq, response, context); if (followup == null) { done = true; } else { if (reuse) { // Make sure the response body is fully consumed, if present HttpEntity entity = response.getEntity(); if (entity != null) { entity.consumeContent(); } // entity consumed above is not an auto-release entity, // need to mark the connection re-usable explicitly managedConn.markReusable(); } else { managedConn.close(); } // check if we can use the same connection for the followup if (!followup.getRoute().equals(roureq.getRoute())) { releaseConnection(); } roureq = followup; } if (managedConn != null && userToken == null) { userToken = userTokenHandler.getUserToken(context); context.setAttribute(ClientContext.USER_TOKEN, userToken); if (userToken != null) { managedConn.setState(userToken); } } } // while not done // check for entity, release connection if possible if ((response == null) || (response.getEntity() == null) || !response.getEntity().isStreaming()) { // connection not needed and (assumed to be) in re-usable state if (reuse) managedConn.markReusable(); releaseConnection(); } else { // install an auto-release entity HttpEntity entity = response.getEntity(); entity = new BasicManagedEntity(entity, managedConn, reuse); response.setEntity(entity); } return response; } catch (HttpException ex) { abortConnection(); throw ex; } catch (IOException ex) { abortConnection(); throw ex; } catch (RuntimeException ex) { abortConnection(); throw ex; } }
From source file:com.hardincoding.sonar.subsonic.service.SubsonicMusicService.java
private void detectRedirect(String originalUrl, Context context, HttpContext httpContext) { HttpUriRequest request = (HttpUriRequest) httpContext.getAttribute(ExecutionContext.HTTP_REQUEST); HttpHost host = (HttpHost) httpContext.getAttribute(ExecutionContext.HTTP_TARGET_HOST); // Sometimes the request doesn't contain the "http://host" part so we // must take from the HttpHost object. String redirectedUrl;/*ww w .j a v a 2 s . co m*/ if (request.getURI().getScheme() == null) { redirectedUrl = host.toURI() + request.getURI(); } else { redirectedUrl = request.getURI().toString(); } redirectFrom = originalUrl.substring(0, originalUrl.indexOf("/rest/")); redirectTo = redirectedUrl.substring(0, redirectedUrl.indexOf("/rest/")); Log.i(TAG, redirectFrom + " redirects to " + redirectTo); redirectionLastChecked = System.currentTimeMillis(); redirectionNetworkType = getCurrentNetworkType(context); }