List of usage examples for org.apache.http.impl.client DefaultHttpClient addResponseInterceptor
public synchronized void addResponseInterceptor(final HttpResponseInterceptor itcp)
From source file:com.bt.download.android.core.HttpFetcher.java
private static HttpClient setupHttpClient(boolean gzip) { SSLSocketFactory.getSocketFactory().setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); SchemeRegistry schemeRegistry = new SchemeRegistry(); schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80)); schemeRegistry.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443)); BasicHttpParams params = new BasicHttpParams(); params.setParameter(ConnManagerPNames.MAX_CONNECTIONS_PER_ROUTE, new ConnPerRouteBean(20)); params.setIntParameter(ConnManagerPNames.MAX_TOTAL_CONNECTIONS, 200); ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager(params, schemeRegistry); DefaultHttpClient httpClient = new DefaultHttpClient(cm, new BasicHttpParams()); httpClient.setHttpRequestRetryHandler(new DefaultHttpRequestRetryHandler(HTTP_RETRY_COUNT, true)); if (gzip) {//from w w w . jav a 2 s .c o m httpClient.addRequestInterceptor(new HttpRequestInterceptor() { public void process(HttpRequest request, HttpContext context) throws HttpException, IOException { if (!request.containsHeader("Accept-Encoding")) { request.addHeader("Accept-Encoding", "gzip"); } } }); httpClient.addResponseInterceptor(new HttpResponseInterceptor() { public void process(HttpResponse response, 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; } } } } }); } return httpClient; }
From source file:sand.actionhandler.weibo.UdaClient.java
private static DefaultHttpClient createHttpClient() { DefaultHttpClient httpclient = new DefaultHttpClient(); 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"); }// www .j av a 2 s . co 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 i = 0; i < codecs.length; i++) { if (codecs[i].getName().equalsIgnoreCase("gzip")) { response.setEntity(new GzipDecompressingEntity(response.getEntity())); return; } } } } }); return httpclient; }
From source file:org.n52.oxf.util.web.GzipEnabledHttpClient.java
private void addGzipInterceptors(DefaultHttpClient httpclient) { httpclient.addRequestInterceptor(new GzipRequestInterceptor()); httpclient.addResponseInterceptor(new GzipResponseInterceptor()); }
From source file:com.rsegismont.androlife.core.utils.AndrolifeUtils.java
private static InputStream getInputStreamFromUrl(Context paramContext, String paramString) { if (confirmDownload(paramContext, paramString)) { try {/* w w w . j a va 2 s . c o m*/ BasicHttpParams localBasicHttpParams = new BasicHttpParams(); HttpConnectionParams.setConnectionTimeout(localBasicHttpParams, 30000); HttpConnectionParams.setSoTimeout(localBasicHttpParams, 30000); DefaultHttpClient localDefaultHttpClient = new DefaultHttpClient(localBasicHttpParams); localDefaultHttpClient.addRequestInterceptor(new HttpRequestInterceptor() { public void process(HttpRequest paramAnonymousHttpRequest, HttpContext paramAnonymousHttpContext) { if (!paramAnonymousHttpRequest.containsHeader(HEADER_ACCEPT_ENCODING)) { paramAnonymousHttpRequest.addHeader(HEADER_ACCEPT_ENCODING, ENCODING_GZIP); } } }); localDefaultHttpClient.addResponseInterceptor(new HttpResponseInterceptor() { public void process(HttpResponse paramAnonymousHttpResponse, HttpContext paramAnonymousHttpContext) { Header localHeader = paramAnonymousHttpResponse.getEntity().getContentEncoding(); HeaderElement[] arrayOfHeaderElement = null; int i; if (localHeader != null) { arrayOfHeaderElement = localHeader.getElements(); i = arrayOfHeaderElement.length; for (int j = 0; j < i; j++) { if (arrayOfHeaderElement[j].getName().equalsIgnoreCase(ENCODING_GZIP)) { paramAnonymousHttpResponse.setEntity(new AndrolifeUtils.InflatingEntity( paramAnonymousHttpResponse.getEntity())); return; } } } } }); InputStream localInputStream = localDefaultHttpClient.execute(new HttpGet(paramString)).getEntity() .getContent(); return localInputStream; } catch (Exception localException) { } return null; } else { return null; } }
From source file:net.oneandone.shared.artifactory.ArtifactoryModule.java
@Provides @Named(value = "httpclient") HttpClient provideHttpClient() {/*from w w w.j av a2s.c o m*/ final DefaultHttpClient client = new DefaultHttpClient(); client.addRequestInterceptor(new RequestAcceptEncoding()); client.addResponseInterceptor(new ResponseContentEncoding()); client.addRequestInterceptor(providePreemptiveRequestInterceptor()); return client; }
From source file:org.jasig.portal.security.provider.saml.SAMLSession.java
/** * Public constructor that initializes the SAML session. This sets up the * ThreadSafeConnectionManager because the connection interceptor will be * making a secondary connection to authenticate to the IdP while the * primary connection is blocked. //from w w w. j a va 2s. c om * * @param samlAssertion SAML assertion that was passed to the portal for authentication * @param connectionManager The connection manager to use for the {@link HttpClient} used for making authenticated requests. The caller is responsible for the {@link ClientConnectionManager} lifecycle. * @param params the {@link HttpClient} configuration parameters to use. */ public SAMLSession(String samlAssertion, ClientConnectionManager connectionManager, HttpParams params) { final DefaultHttpClient client = new DefaultHttpClient(connectionManager, params); client.addRequestInterceptor(new HttpRequestPreprocessor()); client.addResponseInterceptor(new HttpRequestPostprocessor(this)); this.wspHttpClient = client; this.samlAssertion = samlAssertion; }
From source file:com.google.pubsub.clients.common.MetricsHandler.java
private void initialize() { synchronized (this) { try {/*from ww w . j av a 2 s .c o m*/ HttpTransport transport = GoogleNetHttpTransport.newTrustedTransport(); JsonFactory jsonFactory = new JacksonFactory(); GoogleCredential credential = GoogleCredential.getApplicationDefault(transport, jsonFactory); if (credential.createScopedRequired()) { credential = credential.createScoped( Collections.singletonList("https://www.googleapis.com/auth/cloud-platform")); } monitoring = new Monitoring.Builder(transport, jsonFactory, credential) .setApplicationName("Cloud Pub/Sub Loadtest Framework").build(); String zoneId; String instanceId; try { DefaultHttpClient httpClient = new DefaultHttpClient(); httpClient.addRequestInterceptor(new RequestAcceptEncoding()); httpClient.addResponseInterceptor(new ResponseContentEncoding()); HttpConnectionParams.setConnectionTimeout(httpClient.getParams(), 30000); HttpConnectionParams.setSoTimeout(httpClient.getParams(), 30000); HttpConnectionParams.setSoKeepalive(httpClient.getParams(), true); HttpConnectionParams.setStaleCheckingEnabled(httpClient.getParams(), false); HttpConnectionParams.setTcpNoDelay(httpClient.getParams(), true); SchemeRegistry schemeRegistry = httpClient.getConnectionManager().getSchemeRegistry(); schemeRegistry.register(new Scheme("http", 80, PlainSocketFactory.getSocketFactory())); schemeRegistry.register(new Scheme("https", 443, SSLSocketFactory.getSocketFactory())); httpClient.setKeepAliveStrategy((response, ctx) -> 30); HttpGet zoneIdRequest = new HttpGet( "http://metadata.google.internal/computeMetadata/v1/instance/zone"); zoneIdRequest.setHeader("Metadata-Flavor", "Google"); HttpResponse zoneIdResponse = httpClient.execute(zoneIdRequest); String tempZoneId = EntityUtils.toString(zoneIdResponse.getEntity()); if (tempZoneId.lastIndexOf("/") >= 0) { zoneId = tempZoneId.substring(tempZoneId.lastIndexOf("/") + 1); } else { zoneId = tempZoneId; } HttpGet instanceIdRequest = new HttpGet( "http://metadata.google.internal/computeMetadata/v1/instance/id"); instanceIdRequest.setHeader("Metadata-Flavor", "Google"); HttpResponse instanceIdResponse = httpClient.execute(instanceIdRequest); instanceId = EntityUtils.toString(instanceIdResponse.getEntity()); } catch (IOException e) { log.info("Unable to connect to metadata server, assuming not on GCE, setting " + "defaults for instance and zone."); instanceId = "local"; zoneId = "us-east1-b"; // Must use a valid cloud zone even if running local. } monitoredResource.setLabels( ImmutableMap.of("project_id", project, "instance_id", instanceId, "zone", zoneId)); createMetrics(); } catch (IOException e) { log.error("Unable to initialize MetricsHandler, trying again.", e); executor.execute(this::initialize); } catch (GeneralSecurityException e) { log.error("Unable to initialize MetricsHandler permanently, credentials error.", e); } } }
From source file:org.apache.olingo.samples.client.core.http.ProtocolInterceptorHttpClientFactory.java
@Override public DefaultHttpClient create(final HttpMethod method, final URI uri) { final DefaultHttpClient httpClient = super.create(method, uri); httpClient.addRequestInterceptor(new HttpRequestInterceptor() { @Override/*w w w. j av a 2s . co m*/ public void process(final HttpRequest request, final HttpContext context) throws HttpException, IOException { request.addHeader("CUSTOM_HEADER", "CUSTOM VALUE"); } }); httpClient.addResponseInterceptor(new HttpResponseInterceptor() { @Override public void process(final HttpResponse response, final HttpContext context) throws HttpException, IOException { if ("ANOTHER CUSTOM VALUE".equals(response.getFirstHeader("ANOTHER_CUSTOM_HEADER"))) { // do something } } }); return httpClient; }
From source file:com.autonomy.aci.client.transport.impl.HttpClientFactory.java
/** * Creates an instance of <tt>DefaultHttpClient</tt> with a <tt>ThreadSafeClientConnManager</tt>. * @return an implementation of the <tt>HttpClient</tt> interface. *//*from w w w. ja va2 s .c om*/ public HttpClient createInstance() { LOGGER.debug("Creating a new instance of DefaultHttpClient with configuration -> {}", toString()); // Create the connection manager which will be default create the necessary schema registry stuff... final PoolingClientConnectionManager connectionManager = new PoolingClientConnectionManager(); connectionManager.setMaxTotal(maxTotalConnections); connectionManager.setDefaultMaxPerRoute(maxConnectionsPerRoute); // Set the HTTP connection parameters (These are in the HttpCore JavaDocs, NOT the HttpClient ones)... final HttpParams params = new BasicHttpParams(); HttpConnectionParams.setConnectionTimeout(params, connectionTimeout); HttpConnectionParams.setLinger(params, linger); HttpConnectionParams.setSocketBufferSize(params, socketBufferSize); HttpConnectionParams.setSoKeepalive(params, soKeepAlive); HttpConnectionParams.setSoReuseaddr(params, soReuseAddr); HttpConnectionParams.setSoTimeout(params, soTimeout); HttpConnectionParams.setStaleCheckingEnabled(params, staleCheckingEnabled); HttpConnectionParams.setTcpNoDelay(params, tcpNoDelay); // Create the HttpClient and configure the compression interceptors if required... final DefaultHttpClient httpClient = new DefaultHttpClient(connectionManager, params); if (useCompression) { httpClient.addRequestInterceptor(new RequestAcceptEncoding()); httpClient.addResponseInterceptor(new DeflateContentEncoding()); } return httpClient; }
From source file:com.soulgalore.crawler.guice.HttpClientProvider.java
/** * Get the client.//from ww w . j av a 2s . co m * * @return the client */ public HttpClient get() { final ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager(); cm.setMaxTotal(nrOfThreads); cm.setDefaultMaxPerRoute(maxToRoute); final DefaultHttpClient client = HTTPSFaker.getClientThatAllowAnyHTTPS(cm); client.getParams().setParameter("http.socket.timeout", socketTimeout); client.getParams().setParameter("http.connection.timeout", connectionTimeout); client.addRequestInterceptor(new RequestAcceptEncoding()); client.addResponseInterceptor(new ResponseContentEncoding()); CookieSpecFactory csf = new CookieSpecFactory() { public CookieSpec newInstance(HttpParams params) { return new BestMatchSpecWithURLErrorLog(); } }; client.getCookieSpecs().register("bestmatchwithurl", csf); client.getParams().setParameter(ClientPNames.COOKIE_POLICY, "bestmatchwithurl"); if (!"".equals(proxy)) { StringTokenizer token = new StringTokenizer(proxy, ":"); if (token.countTokens() == 3) { String proxyProtocol = token.nextToken(); String proxyHost = token.nextToken(); int proxyPort = Integer.parseInt(token.nextToken()); HttpHost proxy = new HttpHost(proxyHost, proxyPort, proxyProtocol); client.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy); } else System.err.println("Invalid proxy configuration: " + proxy); } if (auths.size() > 0) { for (Auth authObject : auths) { client.getCredentialsProvider().setCredentials( new AuthScope(authObject.getScope(), authObject.getPort()), new UsernamePasswordCredentials(authObject.getUserName(), authObject.getPassword())); } } return client; }