List of usage examples for org.apache.http.impl.client DefaultHttpClient addResponseInterceptor
public synchronized void addResponseInterceptor(final HttpResponseInterceptor itcp)
From source file:com.cloudant.mazha.HttpRequests.java
private void addDebuggingInterceptor(DefaultHttpClient httpclient) { if (!isDebugging()) { return;// ww w . java 2 s. c o m } // request interceptor httpclient.addRequestInterceptor(new HttpRequestInterceptor() { public void process(final HttpRequest request, final HttpContext context) throws IOException { System.out.println(">> " + request.getRequestLine()); } }); // response interceptor httpclient.addResponseInterceptor(new HttpResponseInterceptor() { public void process(final HttpResponse response, final HttpContext context) throws IOException { System.out.println("<< Status: " + response.getStatusLine().getStatusCode()); } }); }
From source file:com.googlecode.noweco.webmail.httpclient.UnsecureHttpClientFactory.java
public DefaultHttpClient createUnsecureHttpClient(final HttpHost proxy) { DefaultHttpClient httpclient = new DefaultHttpClient(new ThreadSafeClientConnManager()); SchemeRegistry schemeRegistry = httpclient.getConnectionManager().getSchemeRegistry(); schemeRegistry.unregister("https"); try {/* w w w .j a v a 2s . c o m*/ SSLContext instance = SSLContext.getInstance("TLS"); TrustManager tm = UnsecureX509TrustManager.INSTANCE; instance.init(null, new TrustManager[] { tm }, null); schemeRegistry.register(new Scheme("https", 443, new SSLSocketFactory(instance, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER))); } catch (Exception e) { throw new RuntimeException("TLS issue", e); } httpclient.removeResponseInterceptorByClass(ResponseProcessCookies.class); httpclient.addResponseInterceptor(new UnsecureResponseProcessCookies()); HttpParams params = httpclient.getParams(); if (proxy != null) { ConnRouteParams.setDefaultProxy(params, proxy); } HttpConnectionParams.setSoTimeout(params, 7000); return httpclient; }
From source file:uk.bowdlerize.API.java
public int ascertainFilteringLevel() { String checkURL = "http://www.reddit.com"; int returnInt = FILTERING_STRICT; DefaultHttpClient client = new DefaultHttpClient(); HttpGet httpGet = new HttpGet(checkURL); httpGet.setHeader("User-Agent", "OONI Android Probe"); try {/* w ww. java 2s .co m*/ client.addResponseInterceptor(new HttpResponseInterceptor() { @Override public void process(HttpResponse httpResponse, HttpContext httpContext) throws HttpException, IOException { if (httpResponse.getStatusLine().getStatusCode() == 302 || httpResponse.getStatusLine().getStatusCode() == 301) { for (Header hdr : httpResponse.getAllHeaders()) { if (hdr.getName().equals("Location")) { checkHeader(hdr); } } } } }); } catch (Exception e) { e.printStackTrace(); return -1; } try { client.execute(httpGet); } catch (CensoredException ce) { return returnInt; } catch (Exception e) { e.printStackTrace(); } returnInt = FILTERING_MEDIUM; checkURL = "http://www.reddit.com/r/nsfw/"; httpGet = new HttpGet(checkURL); try { client.execute(httpGet); } catch (CensoredException ce) { return returnInt; } catch (Exception e) { e.printStackTrace(); } return FILTERING_NONE; }
From source file:mixedserver.protocol.jsonrpc.client.HTTPSession.java
HttpClient http() throws KeyManagementException, UnrecoverableKeyException, NoSuchAlgorithmException, KeyStoreException, CertificateException, IOException { if (client == null) { HttpParams params = new BasicHttpParams(); HttpConnectionParams.setConnectionTimeout(params, getConnectionTimeout()); HttpConnectionParams.setSoTimeout(params, getSoTimeout()); HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); HttpProtocolParams.setContentCharset(params, HTTP.UTF_8); KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); trustStore.load(null, null);//from ww w . ja va 2 s . c om SSLSocketFactory sf = new EasySSLSocketFactory(trustStore); sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); SchemeRegistry registry = new SchemeRegistry(); registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80)); registry.register(new Scheme("https", sf, 443)); /* * ClientConnectionManager mgr = new ThreadSafeClientConnManager( * params, registry); */ ClientConnectionManager mgr = new ThreadSafeClientConnManager(params, registry); DefaultHttpClient defaultHttpClient = new DefaultHttpClient(mgr, params); // gzip? defaultHttpClient.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"); } } }); defaultHttpClient.addResponseInterceptor(new HttpResponseInterceptor() { public void process(final HttpResponse response, final HttpContext context) throws HttpException, IOException { HttpEntity entity = response.getEntity(); if (entity != null) { 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 = defaultHttpClient; } return client; }
From source file:info.novatec.inspectit.rcp.storage.util.DataRetriever.java
/** * Down-loads and saves the file from a {@link CmrRepositoryDefinition}. Files will be saved in * the directory that is denoted as the given Path object. Original file names will be used. * //from w ww. j av a2 s . c om * @param cmrRepositoryDefinition * Repository. * @param files * Map with file names and sizes. * @param postDownloadRunnable * {@link PostDownloadRunnable} that will be executed after successful request. * @param useGzipCompression * If the GZip compression should be used when files are downloaded. * @param decompressContent * If the useGzipCompression is <code>true</code>, this parameter will define if the * received content will be de-compressed. If false is passed content will be saved * to file in the same format as received, but the path of the file will be altered * with additional '.gzip' extension at the end. * @param subMonitor * {@link SubMonitor} for process reporting. * @throws IOException * If {@link IOException} occurs. * @throws BusinessException * If status of HTTP response is not successful (codes 2xx). */ private void downloadAndSaveObjects(CmrRepositoryDefinition cmrRepositoryDefinition, Map<String, Long> files, PostDownloadRunnable postDownloadRunnable, boolean useGzipCompression, boolean decompressContent, final SubMonitor subMonitor) throws IOException, BusinessException { DefaultHttpClient httpClient = new DefaultHttpClient(); final TransferDataMonitor transferDataMonitor = new TransferDataMonitor(subMonitor, files, useGzipCompression); httpClient.addResponseInterceptor(new HttpResponseInterceptor() { @Override public void process(HttpResponse response, HttpContext context) throws HttpException, IOException { response.setEntity(new DownloadHttpEntityWrapper(response.getEntity(), transferDataMonitor)); } }); if (useGzipCompression && decompressContent) { httpClient.addResponseInterceptor(new GzipHttpResponseInterceptor()); } for (Map.Entry<String, Long> fileEntry : files.entrySet()) { String fileName = fileEntry.getKey(); String fileLocation = getServerUri(cmrRepositoryDefinition) + fileName; HttpGet httpGet = new HttpGet(fileLocation); if (useGzipCompression) { httpGet.addHeader("accept-encoding", "gzip"); } transferDataMonitor.startTransfer(fileName); HttpResponse response = httpClient.execute(httpGet); StatusLine statusLine = response.getStatusLine(); if (HttpStatus.valueOf(statusLine.getStatusCode()).series().equals(Series.SUCCESSFUL)) { HttpEntity entity = response.getEntity(); try (InputStream is = entity.getContent()) { postDownloadRunnable.process(is, fileName); } } transferDataMonitor.endTransfer(fileName); } }
From source file:com.flipkart.poseidon.handlers.http.impl.HttpConnectionPool.java
private void addGzipHeaderInRequestResponse() { DefaultHttpClient httpclient = (DefaultHttpClient) this.client; // add Accept-Encoding to all requests httpclient.addRequestInterceptor(new HttpRequestInterceptor() { public void process(final HttpRequest request, final HttpContext context) throws HttpException, IOException { if (isResponseGzipEnabled() && !request.containsHeader(ACCEPT_ENCODING)) { request.addHeader(ACCEPT_ENCODING, COMPRESSION_TYPE); }/*from ww w. jav a 2 s . c o m*/ } }); // if the server sends gzip encoded data, unCompress httpclient.addResponseInterceptor(new HttpResponseInterceptor() { public void process(final HttpResponse response, final HttpContext context) throws HttpException, IOException { HttpEntity entity = response.getEntity(); if (entity != null) { Header ceheader = entity.getContentEncoding(); if (ceheader != null) { HeaderElement[] codecs = ceheader.getElements(); for (int i = 0; i < codecs.length; i++) { if (codecs[i].getName().equalsIgnoreCase(COMPRESSION_TYPE)) { response.setEntity(new GzipDecompressingEntity(response.getEntity())); return; } } } } } }); }
From source file:com.su.search.client.solrj.PaHttpSolrServer.java
/** * Allow server->client communication to be compressed. Currently gzip and * deflate are supported. If the server supports compression the response will * be compressed./*www. j av a 2 s . c om*/ */ public void setAllowCompression(boolean allowCompression) { if (httpClient instanceof DefaultHttpClient) { final DefaultHttpClient client = (DefaultHttpClient) httpClient; client.removeRequestInterceptorByClass(UseCompressionRequestInterceptor.class); client.removeResponseInterceptorByClass(UseCompressionResponseInterceptor.class); if (allowCompression) { client.addRequestInterceptor(new UseCompressionRequestInterceptor()); client.addResponseInterceptor(new UseCompressionResponseInterceptor()); } } else { throw new UnsupportedOperationException("HttpClient instance was not of type DefaultHttpClient"); } }
From source file:com.pc.dailymile.DailyMileClient.java
private void initHttpClient() { HttpParams parameters = new BasicHttpParams(); HttpProtocolParams.setVersion(parameters, HttpVersion.HTTP_1_1); HttpProtocolParams.setContentCharset(parameters, HTTP.DEFAULT_CONTENT_CHARSET); // set the User-Agent to a common User-Agent because currently // the default httpclient User-Agent doesn't work with dailymile HttpProtocolParams.setUserAgent(parameters, "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)"); HttpProtocolParams.setUseExpectContinue(parameters, false); HttpConnectionParams.setTcpNoDelay(parameters, true); SchemeRegistry schReg = new SchemeRegistry(); schReg.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80)); schReg.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443)); ClientConnectionManager tsccm = new ThreadSafeClientConnManager(parameters, schReg); DefaultHttpClient defaultHttpClient = new DefaultHttpClient(tsccm, parameters); defaultHttpClient.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"); }/*from w w w . j a va2 s . c o m*/ } }); defaultHttpClient.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; } } } } }); httpClient = defaultHttpClient; }
From source file:com.controlj.experiment.bulktrend.trendclient.TrendClient.java
public void go() { DefaultHttpClient client = null; try {//from www .jav a 2 s . c o m prepareForResponse(); if (altInput == null) { client = new DefaultHttpClient(); // Set up preemptive Basic Authentication UsernamePasswordCredentials creds = new UsernamePasswordCredentials(user, password); client.getCredentialsProvider().setCredentials(AuthScope.ANY, creds); BasicHttpContext localcontext = new BasicHttpContext(); BasicScheme basicAuth = new BasicScheme(); localcontext.setAttribute("preemptive-auth", basicAuth); client.addRequestInterceptor(new PreemptiveAuthRequestInterceptor(), 0); if (zip) { client.addRequestInterceptor(new GZipRequestInterceptor()); client.addResponseInterceptor(new GZipResponseInterceptor()); } HttpPost post = new HttpPost(url); try { setPostData(post); HttpResponse response = client.execute(post, localcontext); if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) { System.err.println( "Error: Web Service response code of: " + response.getStatusLine().getStatusCode()); return; } HttpEntity entity = response.getEntity(); if (entity != null) { parser.parseResponse(ids.size(), entity.getContent()); } } catch (IOException e) { System.err.println("IO Error reading response"); e.printStackTrace(); } } else { // Alternate input (typically from a file) for testing try { parser.parseResponse(ids.size(), altInput); } catch (IOException e) { System.err.println("IO Error reading response"); e.printStackTrace(); } } } finally { if (client != null) { client.getConnectionManager().shutdown(); } } /* try { parser.parseResponse(ids.size(), new FileInputStream(new File("response.dump"))); } catch (IOException e) { e.printStackTrace(); } */ }
From source file:net.zypr.api.Protocol.java
private DefaultHttpClient getHTTPClient() { DefaultHttpClient httpclient = new DefaultHttpClient(); httpclient.getConnectionManager().getSchemeRegistry().register(new Scheme("https", _socketFactory, 443)); httpclient.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"); }// w w w . j a v a 2s.c o m } }); httpclient.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 index = 0; index < codecs.length; index++) if (codecs[index].getName().equalsIgnoreCase("gzip")) { response.setEntity(new GzipDecompressingEntity(response.getEntity())); return; } } } }); return (httpclient); }