List of usage examples for org.apache.http.protocol ExecutionContext HTTP_REQUEST
String HTTP_REQUEST
To view the source code for org.apache.http.protocol ExecutionContext HTTP_REQUEST.
Click Source Link
From source file:org.apache.abdera2.common.protocol.ClientResponseImpl.java
public String getUri() { HttpUriRequest currentReq = (HttpUriRequest) localContext.getAttribute(ExecutionContext.HTTP_REQUEST); HttpHost currentHost = (HttpHost) localContext.getAttribute(ExecutionContext.HTTP_TARGET_HOST); String currentUrl = currentHost.toURI() + currentReq.getURI(); return currentUrl; }
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 w w w. j a v a 2s . c om*/ }, 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:com.senseidb.svc.impl.HttpRestSenseiServiceImpl.java
private DefaultHttpClient createHttpClient(HttpRequestRetryHandler retryHandler) { HttpParams params = new BasicHttpParams(); SchemeRegistry registry = new SchemeRegistry(); registry.register(new Scheme(_scheme, _port, PlainSocketFactory.getSocketFactory())); ClientConnectionManager cm = new ThreadSafeClientConnManager(registry); DefaultHttpClient client = new DefaultHttpClient(cm, params); if (retryHandler == null) { retryHandler = new HttpRequestRetryHandler() { public boolean retryRequest(IOException exception, int executionCount, HttpContext context) { if (executionCount >= _maxRetries) { // Do not retry if over max retry count return false; }//from w ww. j a v a 2s .c o m 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; } }; } client.setHttpRequestRetryHandler(retryHandler); client.addRequestInterceptor(new HttpRequestInterceptor() { public void process(final HttpRequest request, final HttpContext context) throws HttpException, IOException { if (!request.containsHeader("Accept-Encoding")) { request.addHeader("Accept-Encoding", "gzip"); } } }); client.addResponseInterceptor(new HttpResponseInterceptor() { public void process(final HttpResponse response, final HttpContext context) throws HttpException, IOException { HttpEntity entity = response.getEntity(); Header ceheader = entity.getContentEncoding(); if (ceheader != null) { HeaderElement[] codecs = ceheader.getElements(); for (int i = 0; i < codecs.length; i++) { if (codecs[i].getName().equalsIgnoreCase("gzip")) { response.setEntity(new GzipDecompressingEntity(response.getEntity())); return; } } } } }); client.setKeepAliveStrategy(new DefaultConnectionKeepAliveStrategy() { @Override public long getKeepAliveDuration(HttpResponse response, HttpContext context) { // Honor 'keep-alive' header HeaderElementIterator it = new BasicHeaderElementIterator( response.headerIterator(HTTP.CONN_KEEP_ALIVE)); while (it.hasNext()) { HeaderElement he = it.nextElement(); String param = he.getName(); String value = he.getValue(); if ((value != null) && param.equalsIgnoreCase("timeout")) { try { return Long.parseLong(value) * 1000; } catch (NumberFormatException ignore) { } } } long keepAlive = super.getKeepAliveDuration(response, context); if (keepAlive == -1) { keepAlive = _defaultKeepAliveDurationMS; } return keepAlive; } }); return client; }
From source file:fr.ippon.wip.http.hc.HttpClientExecutor.java
private String getActualUrl(PortletRequest portletRequest, HttpContext context, RequestBuilder request, HttpResponse response) {//from w w w .ja v a 2 s . c om boolean cacheUsed = (context .getAttribute(CachingHttpClient.CACHE_RESPONSE_STATUS) == CacheResponseStatus.CACHE_HIT); boolean notFoundResponse = (response.getStatusLine().getStatusCode() == HttpStatus.SC_NOT_FOUND); /* * ExecutionContext.HTTP_REQUEST and ExecutionContext.HTTP_TARGET_HOST are not set when the cache is used * or when the resource is ignored by WIP */ if (cacheUsed || notFoundResponse) return request.getRequestedURL(); // Get final URL (ie. perhaps redirected) HttpUriRequest actualRequest = (HttpUriRequest) context.getAttribute(ExecutionContext.HTTP_REQUEST); HttpHost actualHost = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST); return (actualRequest.getURI().isAbsolute()) ? actualRequest.getURI().toString() : (actualHost.toURI() + actualRequest.getURI()); }
From source file:mobi.jenkinsci.ci.client.JenkinsFormAuthHttpClient.java
public static String getLatestRedirectedUrl(final HttpContext httpContext) { final HttpRequest request = (HttpRequest) httpContext.getAttribute(ExecutionContext.HTTP_REQUEST); final HttpHost host = (HttpHost) httpContext.getAttribute(ExecutionContext.HTTP_TARGET_HOST); final String requestUri = host.getSchemeName() + "://" + host.getHostName() + (host.getPort() <= 0 ? "" : ":" + host.getPort()) + request.getRequestLine().getUri(); return requestUri; }
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 {//w w w . ja va 2 s .c om 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:org.callimachusproject.client.HttpClientFactoryTest.java
@Test public void test302RedirectTarget() throws Exception { HttpContext localContext = new BasicHttpContext(); HttpGet get = new HttpGet("http://example.com/302"); get.getParams().setBooleanParameter(ClientPNames.HANDLE_REDIRECTS, true); BasicHttpResponse redirect = new BasicHttpResponse(_302); redirect.setHeader("Location", "http://example.com/200"); responses.add(redirect);//from w ww . j a va 2 s . co m responses.add(new BasicHttpResponse(_200)); client.execute(get, new ResponseHandler<Void>() { public Void handleResponse(HttpResponse response) throws ClientProtocolException, IOException { assertEquals(_200.getStatusCode(), response.getStatusLine().getStatusCode()); return null; } }, 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:net.oddsoftware.android.html.HttpCache.java
private void download(CacheItem cacheItem) { try {/*from www .j a v a2 s . com*/ // check to see if file exist, if so check etag and last-modified if (cacheItem.mFilename.length() > 0) { File f = new File(cacheItem.mFilename); try { InputStream is = new FileInputStream(f); is.close(); } catch (IOException exc) { // no file, nuke the cache stats cacheItem.mETag = ""; cacheItem.mLastModified = 0; } } else { cacheItem.mFilename = mCacheDirectory + File.separator + UUID.randomUUID().toString() + ".html.gz"; } HttpContext httpContext = new BasicHttpContext(); HttpClient client = createHttpClient(); HttpUriRequest request = createHttpRequest(cacheItem.mUrl, cacheItem.mETag, cacheItem.mLastModified); if (request == null || request.getURI() == null || request.getURI().getHost() == null || request.getURI().getHost().length() == 0) { if (Globals.LOGGING) Log.e(Globals.LOG_TAG, "unable to create http request for url " + cacheItem.mUrl); return; // sadness } HttpResponse response = client.execute(request, httpContext); StatusLine status = response.getStatusLine(); HttpEntity entity = response.getEntity(); if (status.getStatusCode() == 304) { if (Globals.LOGGING) Log.d(Globals.LOG_TAG, "received 304 not modified"); cacheItem.mHitTime = new Date().getTime(); cacheItem.update(mContentResolver); return; } if (status.getStatusCode() == 200) { InputStream inputStream = null; if (entity != null) { inputStream = entity.getContent(); } else { return; } long contentLength = entity.getContentLength(); if (contentLength > MAX_CONTENT_LENGTH) { if (Globals.LOGGING) Log.w(Globals.LOG_TAG, "HttpCache.download item " + cacheItem.mUrl + " content length is too big " + contentLength); return; } Header encodingHeader = entity.getContentEncoding(); boolean encoded = false; if (encodingHeader != null) { if (encodingHeader.getValue().equalsIgnoreCase("gzip")) { inputStream = new GZIPInputStream(inputStream); encoded = true; } else if (encodingHeader.getValue().equalsIgnoreCase("deflate")) { inputStream = new InflaterInputStream(inputStream); encoded = true; } } File tmpFile = File.createTempFile("httpcache", ".html.gz.tmp", mCacheDirectory); OutputStream os = new GZIPOutputStream(new FileOutputStream(tmpFile)); byte[] buffer = new byte[4096]; int count = 0; long fileSize = 0; while ((count = inputStream.read(buffer)) != -1) { os.write(buffer, 0, count); fileSize += count; } inputStream.close(); os.close(); if (!encoded && contentLength > 0 && fileSize != contentLength) { Log.e(Globals.LOG_TAG, "HttpCache.download: content-length: " + contentLength + " but file size: " + fileSize + " aborting"); tmpFile.delete(); return; } tmpFile.renameTo(new File(cacheItem.mFilename)); // if the parse was ok, update these attributes // ETag: "6050003-78e5-4981d775e87c0" Header etagHeader = response.getFirstHeader("ETag"); if (etagHeader != null) { if (etagHeader.getValue().length() < MAX_ETAG_LENGTH) { cacheItem.mETag = etagHeader.getValue(); } else { if (Globals.LOGGING) Log.e(Globals.LOG_TAG, "etag length was too big: " + etagHeader.getValue().length()); } } // Last-Modified: Fri, 24 Dec 2010 00:57:11 GMT Header lastModifiedHeader = response.getFirstHeader("Last-Modified"); if (lastModifiedHeader != null) { try { cacheItem.mLastModified = FeedManager.parseRFC822Date(lastModifiedHeader.getValue()) .getTime(); } catch (ParseException exc) { if (Globals.LOGGING) Log.e(Globals.LOG_TAG, "unable to parse date", exc); } } // Expires: Thu, 01 Dec 1994 16:00:00 GMT Header expiresHeader = response.getFirstHeader("Expires"); if (expiresHeader != null) { try { cacheItem.mExpiresAt = FeedManager.parseRFC822Date(expiresHeader.getValue()).getTime(); } catch (ParseException exc) { if (Globals.LOGGING) Log.e(Globals.LOG_TAG, "unable to parse expires", exc); } } long now = new Date().getTime() + DEFAULT_EXPIRES; if (cacheItem.mExpiresAt < now) { cacheItem.mExpiresAt = now; } HttpUriRequest currentReq = (HttpUriRequest) httpContext .getAttribute(ExecutionContext.HTTP_REQUEST); HttpHost currentHost = (HttpHost) httpContext.getAttribute(ExecutionContext.HTTP_TARGET_HOST); String currentUrl = currentHost.toURI() + currentReq.getURI(); if (Globals.LOGGING) Log.w(Globals.LOG_TAG, "loaded redirect from " + request.getURI().toString() + " to " + currentUrl); cacheItem.mLastUrl = currentUrl; cacheItem.mHitTime = new Date().getTime(); cacheItem.update(mContentResolver); } } catch (IOException exc) { if (Globals.LOGGING) { Log.e(Globals.LOG_TAG, "error downloading file to cache", exc); } } }