List of usage examples for org.apache.http.impl.client DefaultHttpClient addRequestInterceptor
public synchronized void addRequestInterceptor(final HttpRequestInterceptor itcp)
From source file:org.bimserver.client.Channel.java
public InputStream getDownloadData(String baseAddress, String token, long download, long serializerOid) throws IOException { String address = baseAddress + "/download?token=" + token + "&longActionId=" + download + "&serializerOid=" + serializerOid;//from w ww.j a va 2 s .co m 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"); } } }); 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("gzip")) { response.setEntity(new GzipDecompressingEntity(response.getEntity())); return; } } } } } }); HttpPost httppost = new HttpPost(address); try { HttpResponse httpResponse = httpclient.execute(httppost); if (httpResponse.getStatusLine().getStatusCode() == 200) { return httpResponse.getEntity().getContent(); } else { LOGGER.error(httpResponse.getStatusLine().getStatusCode() + " - " + httpResponse.getStatusLine().getReasonPhrase()); } } catch (ClientProtocolException e) { LOGGER.error("", e); } catch (IOException e) { LOGGER.error("", e); } return null; }
From source file:org.bimserver.client.Channel.java
public long checkin(String baseAddress, String token, long poid, String comment, long deserializerOid, boolean merge, boolean sync, long fileSize, String filename, InputStream inputStream) throws ServerException, UserException { String address = baseAddress + "/upload"; 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"); }/*from www .ja v a2 s.co m*/ } }); 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("gzip")) { response.setEntity(new GzipDecompressingEntity(response.getEntity())); return; } } } } } }); HttpPost httppost = new HttpPost(address); try { // TODO find some GzipInputStream variant that _compresses_ instead of _decompresses_ using deflate for now InputStreamBody data = new InputStreamBody(new DeflaterInputStream(inputStream), filename); MultipartEntity reqEntity = new MultipartEntity(); reqEntity.addPart("data", data); reqEntity.addPart("token", new StringBody(token)); reqEntity.addPart("deserializerOid", new StringBody("" + deserializerOid)); reqEntity.addPart("merge", new StringBody("" + merge)); reqEntity.addPart("poid", new StringBody("" + poid)); reqEntity.addPart("comment", new StringBody("" + comment)); reqEntity.addPart("sync", new StringBody("" + sync)); reqEntity.addPart("compression", new StringBody("deflate")); httppost.setEntity(reqEntity); HttpResponse httpResponse = httpclient.execute(httppost); if (httpResponse.getStatusLine().getStatusCode() == 200) { JsonParser jsonParser = new JsonParser(); JsonElement result = jsonParser .parse(new JsonReader(new InputStreamReader(httpResponse.getEntity().getContent()))); if (result instanceof JsonObject) { JsonObject jsonObject = (JsonObject) result; if (jsonObject.has("exception")) { JsonObject exceptionJson = jsonObject.get("exception").getAsJsonObject(); String exceptionType = exceptionJson.get("__type").getAsString(); String message = exceptionJson.has("message") ? exceptionJson.get("message").getAsString() : "unknown"; if (exceptionType.equals(UserException.class.getSimpleName())) { throw new UserException(message); } else if (exceptionType.equals(ServerException.class.getSimpleName())) { throw new ServerException(message); } } else { return jsonObject.get("checkinid").getAsLong(); } } } } catch (ClientProtocolException e) { LOGGER.error("", e); } catch (IOException e) { LOGGER.error("", e); } return -1; }
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. *//*w w w.ja v a 2 s.co m*/ 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 w w w . j a v a 2 s .c o 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; }
From source file:jetbrains.teamcilty.github.api.impl.HttpClientWrapperImpl.java
public HttpClientWrapperImpl() throws UnrecoverableKeyException, NoSuchAlgorithmException, KeyStoreException, KeyManagementException { final String serverVersion = ServerVersionHolder.getVersion().getDisplayVersion(); final HttpParams ps = new BasicHttpParams(); DefaultHttpClient.setDefaultHttpParams(ps); final int timeout = TeamCityProperties.getInteger("teamcity.github.http.timeout", 300 * 1000); HttpConnectionParams.setConnectionTimeout(ps, timeout); HttpConnectionParams.setSoTimeout(ps, timeout); HttpProtocolParams.setUserAgent(ps, "JetBrains TeamCity " + serverVersion); final SchemeRegistry schemaRegistry = SchemeRegistryFactory.createDefault(); final SSLSocketFactory sslSocketFactory = new SSLSocketFactory(new TrustStrategy() { public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException { return !TeamCityProperties.getBoolean("teamcity.github.verify.ssl.certificate"); }//from w ww . j ava 2 s . c om }); schemaRegistry.register(new Scheme("https", 443, sslSocketFactory)); final DefaultHttpClient httpclient = new DefaultHttpClient(new ThreadSafeClientConnManager(schemaRegistry), ps); setupProxy(httpclient); httpclient.setRoutePlanner(new ProxySelectorRoutePlanner( httpclient.getConnectionManager().getSchemeRegistry(), ProxySelector.getDefault())); httpclient.addRequestInterceptor(new RequestAcceptEncoding()); httpclient.addResponseInterceptor(new ResponseContentEncoding()); httpclient.setHttpRequestRetryHandler(new DefaultHttpRequestRetryHandler(3, true)); myClient = httpclient; }
From source file:com.reachcall.pretty.http.ProxyServlet.java
private HttpClient getClient() { DefaultHttpClient dc = this.clients.checkout(); dc.addRequestInterceptor(this.getHost()); return dc;//from w w w . ja va2 s.com }
From source file:jetbrains.buildServer.commitPublisher.github.api.impl.HttpClientWrapperImpl.java
public HttpClientWrapperImpl() throws UnrecoverableKeyException, NoSuchAlgorithmException, KeyStoreException, KeyManagementException { final String serverVersion = ServerVersionHolder.getVersion().getDisplayVersion(); final HttpParams ps = new BasicHttpParams(); DefaultHttpClient.setDefaultHttpParams(ps); final int timeout = TeamCityProperties.getInteger("teamcity.github.http.timeout", 300 * 1000); HttpConnectionParams.setConnectionTimeout(ps, timeout); HttpConnectionParams.setSoTimeout(ps, timeout); HttpProtocolParams.setUserAgent(ps, "JetBrains TeamCity " + serverVersion); final SchemeRegistry schemaRegistry = SchemeRegistryFactory.createDefault(); final SSLSocketFactory sslSocketFactory = new SSLSocketFactory(new TrustStrategy() { public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException { return !TeamCityProperties.getBoolean("teamcity.github.verify.ssl.certificate"); }/* w ww .ja v a2 s. c o m*/ }) { @Override public Socket connectSocket(int connectTimeout, Socket socket, HttpHost host, InetSocketAddress remoteAddress, InetSocketAddress localAddress, HttpContext context) throws IOException { if (socket instanceof SSLSocket) { try { PropertyUtils.setProperty(socket, "host", host.getHostName()); } catch (Exception ex) { LOG.warn(String.format( "A host name is not passed to SSL connection for the purpose of supporting SNI due to the following exception: %s", ex.toString())); } } return super.connectSocket(connectTimeout, socket, host, remoteAddress, localAddress, context); } }; schemaRegistry.register(new Scheme("https", 443, sslSocketFactory)); final DefaultHttpClient httpclient = new DefaultHttpClient(new ThreadSafeClientConnManager(schemaRegistry), ps); setupProxy(httpclient); httpclient.setRoutePlanner(new ProxySelectorRoutePlanner( httpclient.getConnectionManager().getSchemeRegistry(), ProxySelector.getDefault())); httpclient.addRequestInterceptor(new RequestAcceptEncoding()); httpclient.addResponseInterceptor(new ResponseContentEncoding()); httpclient.setHttpRequestRetryHandler(new DefaultHttpRequestRetryHandler(3, true)); myClient = httpclient; }
From source file:com.cloudant.mazha.HttpRequests.java
private void addDebuggingInterceptor(DefaultHttpClient httpclient) { if (!isDebugging()) { return;//from w w w .ja v a 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: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 www . j a v a 2s. com*/ 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: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 w ww. j a v 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; } } } } } }); }