List of usage examples for org.apache.http.protocol HttpContext getAttribute
Object getAttribute(String str);
From source file:net.ben.subsonic.androidapp.service.RESTMusicService.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); String redirectedUrl = host.toURI() + request.getURI(); 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); }
From source file:com.oakley.fon.util.HttpUtils.java
public static HttpResult getUrlByPost(String url, Map<String, String> params, Map<String, String> headers, int maxRetries) throws IOException { String result = null;/*w w w.j a v a2s .com*/ int retries = 0; HttpContext localContext = new BasicHttpContext(); DefaultHttpClient httpclient = getHttpClient(); List<NameValuePair> formParams = new ArrayList<NameValuePair>(); if (params != null) { Set<Entry<String, String>> paramsSet = params.entrySet(); for (Entry<String, String> entry : paramsSet) { formParams.add(new BasicNameValuePair(entry.getKey(), entry.getValue())); } } UrlEncodedFormEntity postEntity = new UrlEncodedFormEntity(formParams, UTF8); HttpPost httppost = new HttpPost(url); httppost.setEntity(postEntity); if (headers != null) { Set<Entry<String, String>> headersSet = headers.entrySet(); for (Entry<String, String> entry : headersSet) { httppost.setHeader(entry.getKey(), entry.getValue()); } } while (retries < maxRetries && result == null) { try { retries++; HttpEntity responseEntity = httpclient.execute(httppost, localContext).getEntity(); if (responseEntity != null) { result = EntityUtils.toString(responseEntity).trim(); } } catch (SocketException se) { if (retries > maxRetries) { throw se; } else { Log.v(TAG, "SocketException, retrying " + retries, se); } } } HttpHost attribute = (HttpHost) localContext.getAttribute("http.target_host"); String targetHost = null; if (attribute != null) { targetHost = attribute.toURI(); } return new HttpResult(result, (BasicHttpResponse) localContext.getAttribute("http.response"), targetHost); }
From source file:mobi.jenkinsci.ci.client.JenkinsFormAuthHttpClient.java
private void doSsoRedirect(final URL baseUrl, final HttpContext httpContext, String redirectUrl, final String otp) throws IOException { HttpResponse redirectResponse;/*w ww .ja v a 2 s . c om*/ final HttpGet redirect2Jenkins = new HttpGet(redirectUrl); log.debug("Login SUCCEDED: redirecting back to Jenkins using " + redirect2Jenkins.getURI()); try { redirectResponse = httpClient.execute(redirect2Jenkins, httpContext); final HttpHost host = (HttpHost) httpContext.getAttribute(ExecutionContext.HTTP_TARGET_HOST); if (!host.getHostName().toLowerCase().equals(baseUrl.getHost().toLowerCase())) { redirectUrl = getSsoErrorHandler(host).doTwoStepAuthentication(httpClient, httpContext, redirectResponse, otp); doSsoRedirect(baseUrl, httpContext, redirectUrl, null); } if (redirectResponse.getStatusLine().getStatusCode() != HttpURLConnection.HTTP_OK) { throw new IOException("Redirection back to Jenkins failed with HTTP Status Code: " + redirectResponse.getStatusLine()); } } finally { redirect2Jenkins.releaseConnection(); } }
From source file:org.apache.synapse.transport.nhttp.ServerHandler.java
/** * Handle connection timeouts by shutting down the connections * @param conn the connection being processed *//*from w ww. j a v a 2 s . c o m*/ public void timeout(final NHttpServerConnection conn) { HttpContext context = conn.getContext(); Boolean read = (Boolean) context.getAttribute(NhttpConstants.REQUEST_READ); if (read == null || read) { if (log.isDebugEnabled()) { log.debug(conn + ": Keepalive connection was closed"); } shutdownConnection(conn, false, null); } else { String msg = "Connection Timeout - before message body was fully read : " + conn; log.error(msg); if (metrics != null) { metrics.incrementTimeoutsReceiving(); } shutdownConnection(conn, true, msg); } }
From source file:com.google.acre.script.NHttpClient.java
public NHttpClient(int max_connections) { _max_connections = max_connections;/*from ww w. j ava 2 s . c o m*/ _costCollector = CostCollector.getInstance(); BasicHttpProcessor httpproc = new BasicHttpProcessor(); httpproc.addInterceptor(new RequestContent()); httpproc.addInterceptor(new RequestTargetHost()); httpproc.addInterceptor(new RequestConnControl()); httpproc.addInterceptor(new RequestUserAgent()); httpproc.addInterceptor(new RequestExpectContinue()); BufferingHttpClientHandler handler = new BufferingHttpClientHandler(httpproc, new NHttpRequestExecutionHandler(), new DefaultConnectionReuseStrategy(), DEFAULT_HTTP_PARAMS); handler.setEventListener(new EventListener() { private final static String REQUEST_CLOSURE = "request-closure"; public void connectionClosed(NHttpConnection conn) { // pass (should we be logging this?) } public void connectionOpen(NHttpConnection conn) { // pass (should we be logging this?) } public void connectionTimeout(NHttpConnection conn) { noteException(null, conn); } void noteException(Exception e, NHttpConnection conn) { HttpContext context = conn.getContext(); NHttpClientClosure closure = (NHttpClientClosure) context.getAttribute(REQUEST_CLOSURE); if (closure != null) closure.exceptions().add(e); } public void fatalIOException(IOException e, NHttpConnection conn) { noteException(e, conn); } public void fatalProtocolException(HttpException e, NHttpConnection conn) { noteException(e, conn); } }); try { SSLContext sctx = SSLContext.getInstance("SSL"); sctx.init(null, null, null); _dispatch = new NHttpAdaptableSensibleAndLogicalIOEventDispatch(handler, sctx, DEFAULT_HTTP_PARAMS); } catch (java.security.KeyManagementException e) { throw new RuntimeException(e); } catch (java.security.NoSuchAlgorithmException e) { throw new RuntimeException(e); } _requests = new ArrayList<NHttpClientClosure>(); _connection_lock = new Semaphore(_max_connections); }
From source file:org.callimachusproject.client.HttpClientFactoryTest.java
@Test public void testTargetHost() throws Exception { HttpContext localContext = new BasicHttpContext(); responses.add(new BasicHttpResponse(_200)); client.execute(new HttpGet("http://example.com/200"), new ResponseHandler<Void>() { public Void handleResponse(HttpResponse response) throws ClientProtocolException, IOException { assertEquals(_200.getStatusCode(), response.getStatusLine().getStatusCode()); return null; }// w w w.j ava2s.c o m }, localContext); HttpHost host = (HttpHost) localContext.getAttribute(ExecutionContext.HTTP_TARGET_HOST); assertEquals(ORIGIN, host.toString()); }
From source file:org.callimachusproject.client.HttpClientFactoryTest.java
@Test public void testTarget() throws Exception { HttpContext localContext = new BasicHttpContext(); responses.add(new BasicHttpResponse(_200)); client.execute(new HttpGet("http://example.com/200"), new ResponseHandler<Void>() { public Void handleResponse(HttpResponse response) throws ClientProtocolException, IOException { assertEquals(_200.getStatusCode(), response.getStatusLine().getStatusCode()); return null; }//from ww w.j a v a 2s . c o m }, localContext); HttpHost host = (HttpHost) localContext.getAttribute(ExecutionContext.HTTP_TARGET_HOST); HttpUriRequest req = (HttpUriRequest) localContext.getAttribute(ExecutionContext.HTTP_REQUEST); URI root = new URI(host.getSchemeName(), null, host.getHostName(), host.getPort(), "/", null, null); assertEquals("http://example.com/200", root.resolve(req.getURI()).toASCIIString()); }
From source file:wuit.crawler.CrawlerHtml.java
public String doGetHttp(String url) { HttpParams params = new BasicHttpParams(); HttpConnectionParams.setConnectionTimeout(params, 12000); HttpConnectionParams.setSoTimeout(params, 9000); HttpClient httpclient = new DefaultHttpClient(params); String rs = ""; try {/*from w w w . j a v a 2 s . co m*/ HttpGet httpget = new HttpGet(url); System.out.println("executing request " + url); HttpContext httpContext = new BasicHttpContext(); // httpget.addHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)"); httpget.addHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; QQDownload 1.7; .NET CLR 1.1.4322; CIBA; .NET CLR 2.0.50727)"); HttpResponse response = httpclient.execute(httpget, httpContext); HttpUriRequest realRequest = (HttpUriRequest) httpContext.getAttribute(ExecutionContext.HTTP_REQUEST); HttpHost targetHost = (HttpHost) httpContext.getAttribute(ExecutionContext.HTTP_TARGET_HOST); url = targetHost.toString() + realRequest.getURI(); int resStatu = response.getStatusLine().getStatusCode();//? if (resStatu == 200) { HttpEntity entity = response.getEntity(); if (entity != null) { rs = EntityUtils.toString(entity, "iso-8859-1"); String in_code = getEncoding(rs); String encode = getHtmlEncode(rs); if (encode.isEmpty()) { httpclient.getConnectionManager().shutdown(); return ""; } else { if (!in_code.toLowerCase().equals("utf-8") && !in_code.toLowerCase().equals(encode.toLowerCase())) { if (!in_code.toLowerCase().equals("iso-8859-1")) rs = new String(rs.getBytes("iso-8859-1"), in_code); if (!encode.toLowerCase().equals(in_code.toLowerCase())) rs = new String(rs.getBytes(in_code), encode); } } try { } catch (RuntimeException ex) { httpget.abort(); throw ex; } finally { // Closing the input stream will trigger connection release // try { instream.close(); } catch (Exception ignore) {} } } } } finally { // When HttpClient instance is no longer needed, // shut down the connection manager to ensure // immediate deallocation of all system resources httpclient.getConnectionManager().shutdown(); return rs; } }
From source file:eu.europeanaconnect.erds.HTTPResolverMultiThreaded.java
/** * TODO: ->Nuno: explain this part please *//*from ww w .j a v a 2s .co m*/ public HTTPResolverMultiThreaded() { HttpParams params = new BasicHttpParams(); ConnManagerParams.setMaxTotalConnections(params, MAX_CONNECTIONS); ConnPerRouteBean connPerRoute = new ConnPerRouteBean(CONN_PER_ROUTE); ConnManagerParams.setMaxConnectionsPerRoute(params, connPerRoute); SchemeRegistry schemeRegistry = new SchemeRegistry(); schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80)); schemeRegistry.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443)); ClientConnectionManager clientConnectionManager = new ThreadSafeClientConnManager(params, schemeRegistry); this.httpClient = new DefaultHttpClient(clientConnectionManager, params); HttpConnectionParams.setConnectionTimeout(this.httpClient.getParams(), CONECTION_TIMEOUT); HttpConnectionParams.setSoTimeout(this.httpClient.getParams(), SOCKET_TIMEOUT); this.httpClient.getParams().setBooleanParameter(ClientPNames.HANDLE_REDIRECTS, false); this.httpClient.getParams().setBooleanParameter(ClientPNames.REJECT_RELATIVE_REDIRECT, false); this.httpClient.getParams().setParameter(CoreProtocolPNames.USER_AGENT, this.userAgentString); HttpRequestRetryHandler myRetryHandler = new HttpRequestRetryHandler() { @Override public boolean retryRequest(IOException exception, int executionCount, HttpContext context) { if (executionCount >= MAXIMUM_REQUEST_RETRIES) { // Do not retry if over max retry count return false; } if (exception instanceof NoHttpResponseException) { // Retry if the server dropped connection on us return true; } if (exception instanceof SSLHandshakeException) { // Do not retry on SSL handshake exception return false; } HttpRequest request = (HttpRequest) context.getAttribute(ExecutionContext.HTTP_REQUEST); boolean idempotent = !(request instanceof HttpEntityEnclosingRequest); if (idempotent) { // Retry if the request is considered idempotent return true; } return false; } }; this.httpClient.setHttpRequestRetryHandler(myRetryHandler); }