List of usage examples for org.apache.http.impl.client DefaultHttpClient addResponseInterceptor
public synchronized void addResponseInterceptor(final HttpResponseInterceptor itcp)
From source file:com.cloudant.client.org.lightcouch.CouchDbClientAndroid.java
private void registerInterceptors(DefaultHttpClient httpclient) { httpclient.addRequestInterceptor(new HttpRequestInterceptor() { public void process(final HttpRequest request, final HttpContext context) throws IOException { if (log.isInfoEnabled()) { RequestLine req = request.getRequestLine(); log.info("> " + req.getMethod() + URLDecoder.decode(req.getUri(), "UTF-8")); }/*w w w . ja v a 2 s .c om*/ } }); httpclient.addResponseInterceptor(new HttpResponseInterceptor() { public void process(final HttpResponse response, final HttpContext context) throws IOException { if (log.isInfoEnabled()) { log.info("< Status: " + response.getStatusLine().getStatusCode()); } validate(response); } }); }
From source file:org.opensaml.util.http.HttpClientBuilder.java
/** * Constructs an {@link HttpClient} using the settings of this builder. * /* w ww . ja v a2 s. c o m*/ * @return the constructed client */ public HttpClient buildClient() { final DefaultHttpClient client = new DefaultHttpClient(buildConnectionManager()); client.addRequestInterceptor(new RequestAcceptEncoding()); client.addResponseInterceptor(new ResponseContentEncoding()); final HttpParams httpParams = client.getParams(); if (socketLocalAddress != null) { httpParams.setParameter(AllClientPNames.LOCAL_ADDRESS, socketLocalAddress); } if (socketTimeout > 0) { httpParams.setIntParameter(AllClientPNames.SO_TIMEOUT, socketTimeout); } httpParams.setIntParameter(AllClientPNames.SOCKET_BUFFER_SIZE, socketBufferSize); if (connectionTimeout > 0) { httpParams.setIntParameter(AllClientPNames.CONNECTION_TIMEOUT, connectionTimeout); } httpParams.setBooleanParameter(AllClientPNames.STALE_CONNECTION_CHECK, connectionStalecheck); if (connectionProxyHost != null) { final HttpHost proxyHost = new HttpHost(connectionProxyHost, connectionProxyPort); httpParams.setParameter(AllClientPNames.DEFAULT_PROXY, proxyHost); if (connectionProxyUsername != null && connectionProxyPassword != null) { final CredentialsProvider credProvider = client.getCredentialsProvider(); credProvider.setCredentials(new AuthScope(connectionProxyHost, connectionProxyPort), new UsernamePasswordCredentials(connectionProxyUsername, connectionProxyPassword)); } } httpParams.setBooleanParameter(AllClientPNames.HANDLE_REDIRECTS, httpFollowRedirects); httpParams.setParameter(AllClientPNames.HTTP_CONTENT_CHARSET, httpContentCharSet); return client; }
From source file:com.futureplatforms.kirin.internal.attic.IOUtils.java
public static HttpClient newHttpClient() { int timeout = 3 * 60 * 1000; DefaultHttpClient httpClient = new DefaultHttpClient(); ClientConnectionManager mgr = httpClient.getConnectionManager(); HttpParams params = httpClient.getParams(); ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager(params, mgr.getSchemeRegistry()); httpClient = new DefaultHttpClient(cm, params); // how long are we prepared to wait to establish a connection? HttpConnectionParams.setConnectionTimeout(params, timeout); // how long should the socket wait for data? HttpConnectionParams.setSoTimeout(params, timeout); httpClient.setHttpRequestRetryHandler(new DefaultHttpRequestRetryHandler(3, false) { @Override/*w w w . j ava2 s.c o m*/ public boolean retryRequest(IOException exception, int executionCount, HttpContext context) { return super.retryRequest(exception, executionCount, context); } @Override public boolean isRequestSentRetryEnabled() { return false; } }); 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 { response.removeHeaders("Set-Cookie"); HttpEntity entity = response.getEntity(); Header contentEncodingHeader = entity.getContentEncoding(); if (contentEncodingHeader != null) { HeaderElement[] codecs = contentEncodingHeader.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:com.googlecode.sardine.FunctionalSardineTest.java
@Test public void testPutRange() throws Exception { final DefaultHttpClient client = new DefaultHttpClient(); Sardine sardine = new SardineImpl(client); // mod_dav supports Range headers for PUT final String url = "http://sudo.ch/dav/anon/sardine/" + UUID.randomUUID().toString(); client.addResponseInterceptor(new HttpResponseInterceptor() { public void process(final HttpResponse r, final HttpContext context) throws HttpException, IOException { assertEquals(201, r.getStatusLine().getStatusCode()); client.removeResponseInterceptorByClass(this.getClass()); }/*from www . jav a 2 s . c o m*/ }); sardine.put(url, new ByteArrayInputStream("Te".getBytes("UTF-8"))); try { // Append to existing file final Map<String, String> header = Collections.singletonMap(HttpHeaders.CONTENT_RANGE, "bytes " + 2 + "-" + 3 + "/" + 4); client.addRequestInterceptor(new HttpRequestInterceptor() { public void process(final HttpRequest r, final HttpContext context) throws HttpException, IOException { assertNotNull(r.getHeaders(HttpHeaders.CONTENT_RANGE)); assertEquals(1, r.getHeaders(HttpHeaders.CONTENT_RANGE).length); client.removeRequestInterceptorByClass(this.getClass()); } }); client.addResponseInterceptor(new HttpResponseInterceptor() { public void process(final HttpResponse r, final HttpContext context) throws HttpException, IOException { assertEquals(204, r.getStatusLine().getStatusCode()); client.removeResponseInterceptorByClass(this.getClass()); } }); sardine.put(url, new ByteArrayInputStream("st".getBytes("UTF-8")), header); assertEquals("Test", new BufferedReader(new InputStreamReader(sardine.get(url), "UTF-8")).readLine()); } finally { sardine.delete(url); } }
From source file:com.ryan.ryanreader.cache.CacheManager.java
private CacheManager(final Context context) { if (!isAlreadyInitialized.compareAndSet(false, true)) { throw new RuntimeException("Attempt to initialize the cache twice."); }// w w w.j a v a 2s . co m this.context = context; dbManager = new CacheDbManager(context); requestHandler = new RequestHandlerThread(); // TODo put somewhere else -- make request specific, no restart needed on prefs change! final HttpParams params = new BasicHttpParams(); params.setParameter(CoreProtocolPNames.USER_AGENT, Constants.ua(context)); params.setParameter(CoreConnectionPNames.SO_TIMEOUT, 20000); // TODO remove hardcoded params, put in network prefs params.setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 20000); params.setParameter(CoreConnectionPNames.MAX_HEADER_COUNT, 100); params.setParameter(ClientPNames.HANDLE_REDIRECTS, true); params.setParameter(ClientPNames.MAX_REDIRECTS, 2); params.setParameter(ConnManagerPNames.MAX_TOTAL_CONNECTIONS, 50); params.setParameter(ConnManagerPNames.MAX_CONNECTIONS_PER_ROUTE, new ConnPerRoute() { public int getMaxForRoute(HttpRoute route) { return 25; } }); final SchemeRegistry schemeRegistry = new SchemeRegistry(); schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80)); schemeRegistry.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443)); final ThreadSafeClientConnManager connManager = new ThreadSafeClientConnManager(params, schemeRegistry); final DefaultHttpClient defaultHttpClient = new DefaultHttpClient(connManager, params); defaultHttpClient.setHttpRequestRetryHandler(new DefaultHttpRequestRetryHandler(3, true)); defaultHttpClient.addResponseInterceptor(new HttpResponseInterceptor() { public void process(final HttpResponse response, final HttpContext context) throws HttpException, IOException { final HttpEntity entity = response.getEntity(); final Header encHeader = entity.getContentEncoding(); if (encHeader == null) return; for (final HeaderElement elem : encHeader.getElements()) { if ("gzip".equalsIgnoreCase(elem.getName())) { response.setEntity(new GzipDecompressingEntity(entity)); return; } } } }); downloadQueue = new PrioritisedDownloadQueue(defaultHttpClient); requestHandler.start(); for (int i = 0; i < 5; i++) { // TODO remove constant --- customizable final CacheDownloadThread downloadThread = new CacheDownloadThread(downloadQueue, true); downloadThreads.add(downloadThread); } }
From source file:org.dasein.security.joyent.DefaultClientFactory.java
@Override public @Nonnull HttpClient getClient(String endpoint) throws CloudException, InternalException { if (providerContext == null) { throw new CloudException("No context was defined for this request"); }/*from w w w . jav a 2 s.c om*/ final HttpParams params = new BasicHttpParams(); HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); HttpProtocolParams.setContentCharset(params, Consts.UTF_8.toString()); HttpProtocolParams.setUserAgent(params, "Dasein Cloud"); Properties p = providerContext.getCustomProperties(); if (p != null) { String proxyHost = p.getProperty("proxyHost"); String proxyPortStr = p.getProperty("proxyPort"); int proxyPort = 0; if (proxyPortStr != null) { proxyPort = Integer.parseInt(proxyPortStr); } if (proxyHost != null && proxyHost.length() > 0 && proxyPort > 0) { params.setParameter(ConnRoutePNames.DEFAULT_PROXY, new HttpHost(proxyHost, proxyPort)); } } DefaultHttpClient client = new DefaultHttpClient(params); // Joyent does not support gzip at the moment (7.2), but in case it will // in the future we might just leave these here 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"); } request.setParams(params); } }); client.addResponseInterceptor(new HttpResponseInterceptor() { public void process(final HttpResponse response, final HttpContext context) throws HttpException, IOException { HttpEntity entity = response.getEntity(); if (entity != null) { Header header = entity.getContentEncoding(); if (header != null) { for (HeaderElement codec : header.getElements()) { if (codec.getName().equalsIgnoreCase("gzip")) { response.setEntity(new GzipDecompressingEntity(response.getEntity())); break; } } } } } }); return client; }
From source file:org.lol.reddit.cache.CacheManager.java
private CacheManager(final Context context) { if (!isAlreadyInitialized.compareAndSet(false, true)) { throw new RuntimeException("Attempt to initialize the cache twice."); }/*from ww w .j ava 2 s . c o m*/ this.context = context; dbManager = new CacheDbManager(context); RequestHandlerThread requestHandler = new RequestHandlerThread(); // TODo put somewhere else -- make request specific, no restart needed on prefs change! final HttpParams params = new BasicHttpParams(); params.setParameter(CoreProtocolPNames.USER_AGENT, Constants.ua(context)); params.setParameter(CoreConnectionPNames.SO_TIMEOUT, 20000); // TODO remove hardcoded params, put in network prefs params.setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 20000); params.setParameter(CoreConnectionPNames.MAX_HEADER_COUNT, 100); params.setParameter(ClientPNames.HANDLE_REDIRECTS, true); params.setParameter(ClientPNames.MAX_REDIRECTS, 5); params.setParameter(ConnManagerPNames.MAX_TOTAL_CONNECTIONS, 50); params.setParameter(ConnManagerPNames.MAX_CONNECTIONS_PER_ROUTE, new ConnPerRoute() { public int getMaxForRoute(HttpRoute route) { return 25; } }); final SchemeRegistry schemeRegistry = new SchemeRegistry(); schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80)); schemeRegistry.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443)); final ThreadSafeClientConnManager connManager = new ThreadSafeClientConnManager(params, schemeRegistry); final DefaultHttpClient defaultHttpClient = new DefaultHttpClient(connManager, params); defaultHttpClient.setHttpRequestRetryHandler(new DefaultHttpRequestRetryHandler(3, true)); defaultHttpClient.addResponseInterceptor(new HttpResponseInterceptor() { public void process(final HttpResponse response, final HttpContext context) throws HttpException, IOException { final HttpEntity entity = response.getEntity(); final Header encHeader = entity.getContentEncoding(); if (encHeader == null) return; for (final HeaderElement elem : encHeader.getElements()) { if ("gzip".equalsIgnoreCase(elem.getName())) { response.setEntity(new GzipDecompressingEntity(entity)); return; } } } }); downloadQueue = new PrioritisedDownloadQueue(defaultHttpClient); requestHandler.start(); }
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 w w. jav a2s . c om*/ 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.dasein.cloud.digitalocean.DigitalOcean.java
public @Nonnull HttpClient getClient(boolean multipart) throws InternalException { ProviderContext ctx = getContext();// w ww . j a v a2s . c o m if (ctx == null) { throw new InternalException("No context was specified for this request"); } final HttpParams params = new BasicHttpParams(); int timeout = 15000; HttpConnectionParams.setConnectionTimeout(params, timeout); HttpConnectionParams.setSoTimeout(params, timeout); HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); if (!multipart) { HttpProtocolParams.setContentCharset(params, Consts.UTF_8.toString()); } HttpProtocolParams.setUserAgent(params, "Dasein Cloud"); Properties p = ctx.getCustomProperties(); if (p != null) { String proxyHost = p.getProperty("proxyHost"); String proxyPortStr = p.getProperty("proxyPort"); int proxyPort = 0; if (proxyPortStr != null) { proxyPort = Integer.parseInt(proxyPortStr); } if (proxyHost != null && proxyHost.length() > 0 && proxyPort > 0) { params.setParameter(ConnRoutePNames.DEFAULT_PROXY, new HttpHost(proxyHost, proxyPort)); } } DefaultHttpClient client = new DefaultHttpClient(params); 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"); } request.setParams(params); } }); client.addResponseInterceptor(new HttpResponseInterceptor() { public void process(final HttpResponse response, final HttpContext context) throws HttpException, IOException { HttpEntity entity = response.getEntity(); if (entity != null) { Header header = entity.getContentEncoding(); if (header != null) { for (HeaderElement codec : header.getElements()) { if (codec.getName().equalsIgnoreCase("gzip")) { response.setEntity(new GzipDecompressingEntity(response.getEntity())); break; } } } } } }); return client; }
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 w w w. ja 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(); 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; }