List of usage examples for org.apache.http.params HttpParams setParameter
HttpParams setParameter(String str, Object obj);
From source file:vitkin.sfdc.mojo.wsdl.WsdlDownloadlMojo.java
/** * Get an existing HTTP client for the current instance or create a new * one.<br/>// w w w . j a va 2 s . c om * When creating a new HTTP client, try to load previously saved cookies. * * @return HTTP client for the current environment and username. */ private InnerHttpClient getHttpClient() { final String env = useSandbox ? "sanbox" : "dev-prod"; final String clientId = env + '/' + username; InnerHttpClient client = clients.get(clientId); if (client == null) { client = new InnerHttpClient(env); final HttpParams params = client.getParams(); HttpClientParams.setCookiePolicy(params, CookiePolicy.NETSCAPE); params.setParameter(HttpConnectionParams.CONNECTION_TIMEOUT, 30000); clients.put(clientId, client); } return client; }
From source file:com.fuseim.webapp.ProxyServlet.java
@Override public void init() throws ServletException { String doLogStr = getConfigParam(P_LOG); if (doLogStr != null) { this.doLog = Boolean.parseBoolean(doLogStr); }//from w ww . jav a2 s . c o m String doForwardIPString = getConfigParam(P_FORWARDEDFOR); if (doForwardIPString != null) { this.doForwardIP = Boolean.parseBoolean(doForwardIPString); } String preserveHostString = getConfigParam(P_PRESERVEHOST); if (preserveHostString != null) { this.doPreserveHost = Boolean.parseBoolean(preserveHostString); } String preserveCookiesString = getConfigParam(P_PRESERVECOOKIES); if (preserveCookiesString != null) { this.doPreserveCookies = Boolean.parseBoolean(preserveCookiesString); } initTarget(); //sets target* HttpParams hcParams = new BasicHttpParams(); hcParams.setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.IGNORE_COOKIES); hcParams.setBooleanParameter(ClientPNames.HANDLE_REDIRECTS, false); // See #70 readConfigParam(hcParams, ClientPNames.HANDLE_REDIRECTS, Boolean.class); proxyClient = createHttpClient(hcParams); }
From source file:com.google.gwt.jolokia.server.servlet.ProxyServlet.java
@Override public void init() throws ServletException { String doLogStr = getConfigParam(P_LOG); if (doLogStr != null) { this.doLog = Boolean.parseBoolean(doLogStr); }//from w ww . j av a 2s.co m String doForwardIPString = getConfigParam(P_FORWARDEDFOR); if (doForwardIPString != null) { this.doForwardIP = Boolean.parseBoolean(doForwardIPString); } initTarget();// sets target* HttpParams hcParams = new BasicHttpParams(); hcParams.setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.IGNORE_COOKIES); readConfigParam(hcParams, ClientPNames.HANDLE_REDIRECTS, Boolean.class); proxyClient = createHttpClient(hcParams); }
From source file:com.nesscomputing.httpclient.factory.httpclient4.ApacheHttpClient4Factory.java
private <T> void contributeParameters(final DefaultHttpClient httpClient, final HttpRequestBase httpRequest, final HttpClientRequest<T> httpClientRequest) { final Map<String, Object> parameters = httpClientRequest.getParameters(); if (parameters != null && !parameters.isEmpty()) { HttpParams clientParams = httpClient.getParams(); HttpParams requestParams = httpRequest.getParams(); for (Map.Entry<String, Object> entry : parameters.entrySet()) { clientParams.setParameter(entry.getKey(), entry.getValue()); requestParams.setParameter(entry.getKey(), entry.getValue()); }//w ww . j a v a 2 s. c o m } }
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 ww . ja va 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.gege.caldavsyncadapter.caldav.CaldavFacade.java
protected HttpClient getHttpClient() { HttpParams params = new BasicHttpParams(); params.setParameter(ConnManagerPNames.MAX_TOTAL_CONNECTIONS, 30); params.setParameter(ConnManagerPNames.MAX_CONNECTIONS_PER_ROUTE, new ConnPerRouteBean(30)); params.setParameter(HttpProtocolParams.USE_EXPECT_CONTINUE, false); HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); SchemeRegistry registry = new SchemeRegistry(); registry.register(new Scheme("http", new PlainSocketFactory(), 80)); registry.register(new Scheme("https", (trustAll ? EasySSLSocketFactory.getSocketFactory() : SSLSocketFactory.getSocketFactory()), 443)); DefaultHttpClient client = new DefaultHttpClient(new ThreadSafeClientConnManager(params, registry), params); return client; }
From source file:org.opendatakit.common.security.spring.Oauth2ResourceFilter.java
private Map<String, Object> getJsonResponse(String url, String accessToken) { Map<String, Object> nullData = new HashMap<String, Object>(); // OK if we got here, we have a valid token. // Issue the request... URI nakedUri;//w w w .j a v a 2 s . c om try { nakedUri = new URI(url); } catch (URISyntaxException e2) { e2.printStackTrace(); logger.error(e2.toString()); return nullData; } List<NameValuePair> qparams = new ArrayList<NameValuePair>(); qparams.add(new BasicNameValuePair("access_token", accessToken)); URI uri; try { uri = new URI(nakedUri.getScheme(), nakedUri.getUserInfo(), nakedUri.getHost(), nakedUri.getPort(), nakedUri.getPath(), URLEncodedUtils.format(qparams, "UTF-8"), null); } catch (URISyntaxException e1) { e1.printStackTrace(); logger.error(e1.toString()); return nullData; } // DON'T NEED clientId on the toke request... // addCredentials(clientId, clientSecret, nakedUri.getHost()); // setup request interceptor to do preemptive auth // ((DefaultHttpClient) client).addRequestInterceptor(getPreemptiveAuth(), 0); HttpParams httpParams = new BasicHttpParams(); HttpConnectionParams.setConnectionTimeout(httpParams, SERVICE_TIMEOUT_MILLISECONDS); HttpConnectionParams.setSoTimeout(httpParams, SOCKET_ESTABLISHMENT_TIMEOUT_MILLISECONDS); // support redirecting to handle http: => https: transition HttpClientParams.setRedirecting(httpParams, true); // support authenticating HttpClientParams.setAuthenticating(httpParams, true); httpParams.setParameter(ClientPNames.MAX_REDIRECTS, 1); httpParams.setParameter(ClientPNames.ALLOW_CIRCULAR_REDIRECTS, true); // setup client HttpClient client = httpClientFactory.createHttpClient(httpParams); HttpGet httpget = new HttpGet(uri); logger.info(httpget.getURI().toString()); HttpResponse response = null; try { response = client.execute(httpget, new BasicHttpContext()); int statusCode = response.getStatusLine().getStatusCode(); if (statusCode != HttpStatus.SC_OK) { logger.error("not 200: " + statusCode); return nullData; } else { HttpEntity entity = response.getEntity(); if (entity != null && entity.getContentType().getValue().toLowerCase().contains("json")) { BufferedReader reader = null; InputStreamReader isr = null; try { reader = new BufferedReader(isr = new InputStreamReader(entity.getContent())); @SuppressWarnings("unchecked") Map<String, Object> userData = mapper.readValue(reader, Map.class); return userData; } finally { if (reader != null) { try { reader.close(); } catch (IOException e) { // ignore } } if (isr != null) { try { isr.close(); } catch (IOException e) { // ignore } } } } else { logger.error("unexpected body"); return nullData; } } } catch (IOException e) { logger.error(e.toString()); return nullData; } catch (Exception e) { logger.error(e.toString()); return nullData; } }
From source file:com.swater.meimeng.activity.oomimg.ImageCache.java
/** * Blocking call to download an image. The image is placed directly into the disk cache at the * given key./*from w w w .java 2s . c om*/ * * @param uri * the location of the image * @return a decoded bitmap * @throws org.apache.http.client.ClientProtocolException * if the HTTP response code wasn't 200 or any other HTTP errors * @throws java.io.IOException */ protected void downloadImage(String key, Uri uri) throws ClientProtocolException, IOException { if (DEBUG) { Log.d(TAG, "downloadImage(" + key + ", " + uri + ")"); } if (USE_APACHE_NC) { final HttpGet get = new HttpGet(uri.toString()); final HttpParams params = get.getParams(); params.setParameter(ClientPNames.HANDLE_REDIRECTS, true); final HttpResponse hr = hc.execute(get); final StatusLine hs = hr.getStatusLine(); if (hs.getStatusCode() != 200) { throw new HttpResponseException(hs.getStatusCode(), hs.getReasonPhrase()); } final HttpEntity ent = hr.getEntity(); // TODO I think this means that the source file must be a jpeg. fix this. try { putRaw(key, ent.getContent()); if (DEBUG) { Log.d(TAG, "source file of " + uri + " saved to disk cache at location " + getFile(key).getAbsolutePath()); } } finally { ent.consumeContent(); } } else { final URLConnection con = new URL(uri.toString()).openConnection(); putRaw(key, con.getInputStream()); if (DEBUG) { Log.d(TAG, "source file of " + uri + " saved to disk cache at location " + getFile(key).getAbsolutePath()); } } }
From source file:com.akop.bach.ImageCache.java
public Bitmap getBitmap(String imageUrl, CachePolicy cachePol) { if (imageUrl == null || imageUrl.length() < 1) return null; File file = getCacheFile(imageUrl, cachePol); // See if it's in the local cache // (but only if not being forced to refresh) if (!cachePol.bypassCache && file.canRead()) { if (App.getConfig().logToConsole()) App.logv("Cache hit: " + file.getName()); try {/*w ww . jav a 2 s. c o m*/ if (!cachePol.expired(System.currentTimeMillis(), file.lastModified())) return BitmapFactory.decodeFile(file.getAbsolutePath()); } catch (OutOfMemoryError e) { return null; } } // Fetch the image byte[] blob; int length; try { HttpClient client = new IgnorantHttpClient(); HttpParams params = client.getParams(); params.setParameter("http.useragent", "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0;)"); HttpConnectionParams.setConnectionTimeout(params, TIMEOUT_MS); HttpConnectionParams.setSoTimeout(params, TIMEOUT_MS); HttpResponse resp = client.execute(new HttpGet(imageUrl)); HttpEntity entity = resp.getEntity(); if (entity == null) return null; InputStream stream = entity.getContent(); if (stream == null) return null; try { if ((length = (int) entity.getContentLength()) <= 0) { // Length is negative, perhaps content length is not set ByteArrayOutputStream byteStream = new ByteArrayOutputStream(); int chunkSize = 5000; byte[] chunk = new byte[chunkSize]; for (int r = 0; r >= 0; r = stream.read(chunk, 0, chunkSize)) byteStream.write(chunk, 0, r); blob = byteStream.toByteArray(); } else { // We know the length blob = new byte[length]; // Read the stream until nothing more to read for (int r = 0; r < length; r += stream.read(blob, r, length - r)) ; } } finally { stream.close(); entity.consumeContent(); } } catch (IOException e) { if (App.getConfig().logToConsole()) e.printStackTrace(); return null; } // if (file.canWrite()) { FileOutputStream fos = null; try { fos = new FileOutputStream(file); if (cachePol.resizeWidth > 0 || cachePol.resizeHeight > 0) { Bitmap bmp = BitmapFactory.decodeByteArray(blob, 0, blob.length); float aspectRatio = (float) bmp.getWidth() / (float) bmp.getHeight(); int newWidth = (cachePol.resizeWidth <= 0) ? (int) ((float) cachePol.resizeHeight * aspectRatio) : cachePol.resizeWidth; int newHeight = (cachePol.resizeHeight <= 0) ? (int) ((float) cachePol.resizeWidth / aspectRatio) : cachePol.resizeHeight; Bitmap resized = Bitmap.createScaledBitmap(bmp, newWidth, newHeight, true); resized.compress(Bitmap.CompressFormat.PNG, 100, fos); return resized; } else { fos.write(blob); } if (App.getConfig().logToConsole()) App.logv("Wrote to cache: " + file.getName()); } catch (IOException e) { if (App.getConfig().logToConsole()) e.printStackTrace(); } finally { if (fos != null) { try { fos.close(); } catch (IOException e) { } } } } Bitmap bmp = null; try { bmp = BitmapFactory.decodeByteArray(blob, 0, blob.length); } catch (Exception e) { if (App.getConfig().logToConsole()) e.printStackTrace(); } return bmp; }