List of usage examples for org.apache.http.params HttpParams setParameter
HttpParams setParameter(String str, Object obj);
From source file:org.apache.axis2.transport.http.impl.httpclient4.HTTPSenderImpl.java
protected AbstractHttpClient getHttpClient(MessageContext msgContext) { ConfigurationContext configContext = msgContext.getConfigurationContext(); AbstractHttpClient httpClient = (AbstractHttpClient) msgContext .getProperty(HTTPConstants.CACHED_HTTP_CLIENT); if (httpClient == null) { httpClient = (AbstractHttpClient) configContext.getProperty(HTTPConstants.CACHED_HTTP_CLIENT); }//from w w w . j a va 2 s. co m if (httpClient != null) { return httpClient; } synchronized (this) { httpClient = (AbstractHttpClient) msgContext.getProperty(HTTPConstants.CACHED_HTTP_CLIENT); if (httpClient == null) { httpClient = (AbstractHttpClient) configContext.getProperty(HTTPConstants.CACHED_HTTP_CLIENT); } if (httpClient != null) { return httpClient; } ClientConnectionManager connManager = (ClientConnectionManager) msgContext .getProperty(HTTPConstants.MULTITHREAD_HTTP_CONNECTION_MANAGER); if (connManager == null) { connManager = (ClientConnectionManager) msgContext .getProperty(HTTPConstants.MULTITHREAD_HTTP_CONNECTION_MANAGER); } if (connManager == null) { // reuse HttpConnectionManager synchronized (configContext) { connManager = (ClientConnectionManager) configContext .getProperty(HTTPConstants.MULTITHREAD_HTTP_CONNECTION_MANAGER); if (connManager == null) { log.trace("Making new ConnectionManager"); SchemeRegistry schemeRegistry = new SchemeRegistry(); schemeRegistry.register(new Scheme("http", 80, PlainSocketFactory.getSocketFactory())); schemeRegistry.register(new Scheme("https", 443, SSLSocketFactory.getSocketFactory())); connManager = new PoolingClientConnectionManager(schemeRegistry); ((PoolingClientConnectionManager) connManager).setMaxTotal(200); ((PoolingClientConnectionManager) connManager).setDefaultMaxPerRoute(200); configContext.setProperty(HTTPConstants.MULTITHREAD_HTTP_CONNECTION_MANAGER, connManager); } } } /* * Create a new instance of HttpClient since the way it is used here * it's not fully thread-safe. */ HttpParams clientParams = new BasicHttpParams(); clientParams.setParameter(CoreProtocolPNames.HTTP_ELEMENT_CHARSET, "UTF-8"); httpClient = new DefaultHttpClient(connManager, clientParams); //We don't need to set timeout for connection manager, since we are doing it below // and its enough // Get the timeout values set in the runtime initializeTimeouts(msgContext, httpClient); return httpClient; } }
From source file:org.dasein.cloud.terremark.TerremarkMethod.java
public Document invoke(boolean debug) throws TerremarkException, CloudException, InternalException { if (logger.isTraceEnabled()) { logger.trace("ENTER - " + TerremarkMethod.class.getName() + ".invoke(" + debug + ")"); }//from w w w . j a v a 2 s .c o m try { if (logger.isDebugEnabled()) { logger.debug("Talking to server at " + url); } if (parameters != null) { URIBuilder uri = null; try { uri = new URIBuilder(url); } catch (URISyntaxException e) { e.printStackTrace(); } for (NameValuePair parameter : parameters) { uri.addParameter(parameter.getName(), parameter.getValue()); } url = uri.toString(); } HttpUriRequest method = null; if (methodType.equals(HttpMethodName.GET)) { method = new HttpGet(url); } else if (methodType.equals(HttpMethodName.POST)) { method = new HttpPost(url); } else if (methodType.equals(HttpMethodName.DELETE)) { method = new HttpDelete(url); } else if (methodType.equals(HttpMethodName.PUT)) { method = new HttpPut(url); } else if (methodType.equals(HttpMethodName.HEAD)) { method = new HttpHead(url); } else { method = new HttpGet(url); } HttpResponse status = null; try { HttpClient client = new DefaultHttpClient(); HttpParams params = new BasicHttpParams(); HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); HttpProtocolParams.setContentCharset(params, "UTF-8"); HttpProtocolParams.setUserAgent(params, "Dasein Cloud"); attempts++; String proxyHost = provider.getProxyHost(); if (proxyHost != null) { int proxyPort = provider.getProxyPort(); boolean ssl = url.startsWith("https"); params.setParameter(ConnRoutePNames.DEFAULT_PROXY, new HttpHost(proxyHost, proxyPort, ssl ? "https" : "http")); } for (Map.Entry<String, String> entry : headers.entrySet()) { method.addHeader(entry.getKey(), entry.getValue()); } if (body != null && body != "" && (methodType.equals(HttpMethodName.PUT) || methodType.equals(HttpMethodName.POST))) { try { HttpEntity entity = new StringEntity(body, "UTF-8"); ((HttpEntityEnclosingRequestBase) method).setEntity(entity); } catch (UnsupportedEncodingException e) { logger.warn(e); } } if (wire.isDebugEnabled()) { wire.debug(methodType.name() + " " + method.getURI()); for (Header header : method.getAllHeaders()) { wire.debug(header.getName() + ": " + header.getValue()); } if (body != null) { wire.debug(body); } } try { status = client.execute(method); if (wire.isDebugEnabled()) { wire.debug("HTTP STATUS: " + status); } } catch (IOException e) { logger.error("I/O error from server communications: " + e.getMessage()); e.printStackTrace(); throw new InternalException(e); } int statusCode = status.getStatusLine().getStatusCode(); if (statusCode == HttpStatus.SC_OK || statusCode == HttpStatus.SC_CREATED || statusCode == HttpStatus.SC_ACCEPTED) { try { InputStream input = status.getEntity().getContent(); try { return parseResponse(input); } finally { input.close(); } } catch (IOException e) { logger.error("Error parsing response from Teremark: " + e.getMessage()); e.printStackTrace(); throw new CloudException(CloudErrorType.COMMUNICATION, statusCode, null, e.getMessage()); } } else if (statusCode == HttpStatus.SC_NO_CONTENT) { logger.debug("Recieved no content in response. Creating an empty doc."); DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = null; try { docBuilder = dbfac.newDocumentBuilder(); } catch (ParserConfigurationException e) { e.printStackTrace(); } return docBuilder.newDocument(); } else if (statusCode == HttpStatus.SC_FORBIDDEN) { String msg = "OperationNotAllowed "; try { msg += parseResponseToString(status.getEntity().getContent()); } catch (IllegalStateException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } wire.error(msg); throw new TerremarkException(statusCode, "OperationNotAllowed", msg); } else { String response = "Failed to parse response."; ParsedError parsedError = null; try { response = parseResponseToString(status.getEntity().getContent()); parsedError = parseErrorResponse(response); } catch (IllegalStateException e1) { e1.printStackTrace(); } catch (IOException e1) { e1.printStackTrace(); } if (logger.isDebugEnabled()) { logger.debug("Received " + status + " from " + url); } if (statusCode == HttpStatus.SC_SERVICE_UNAVAILABLE || statusCode == HttpStatus.SC_INTERNAL_SERVER_ERROR) { if (attempts >= 5) { String msg; wire.warn(response); if (statusCode == HttpStatus.SC_SERVICE_UNAVAILABLE) { msg = "Cloud service is currently unavailable."; } else { msg = "The cloud service encountered a server error while processing your request."; try { msg = msg + "Response from server was:\n" + response; } catch (RuntimeException runException) { logger.warn(runException); } catch (Error error) { logger.warn(error); } } wire.error(response); logger.error(msg); if (parsedError != null) { throw new TerremarkException(parsedError); } else { throw new CloudException("HTTP Status " + statusCode + msg); } } else { try { Thread.sleep(5000L); } catch (InterruptedException e) { /* ignore */ } return invoke(); } } wire.error(response); if (parsedError != null) { throw new TerremarkException(parsedError); } else { String msg = "\nResponse from server was:\n" + response; logger.error(msg); throw new CloudException("HTTP Status " + statusCode + msg); } } } finally { try { if (status != null) { EntityUtils.consume(status.getEntity()); } } catch (IOException e) { e.printStackTrace(); } } } finally { if (logger.isTraceEnabled()) { logger.trace("EXIT - " + TerremarkMethod.class.getName() + ".invoke()"); } } }
From source file:org.eclipse.b3.p2.maven.loader.Maven2RepositoryLoader.java
private boolean isFolder(URI uri) { IPath path = Path.fromPortableString(uri.getPath()); if (path.hasTrailingSeparator()) return true; String scheme = uri.getScheme(); if ("http".equals(scheme) || "https".equals(scheme)) { HttpGet request = new HttpGet(uri.toString()); HttpClient httpClient = new DefaultHttpClient(); try {//from w ww. ja v a 2 s .co m HttpParams params = new BasicHttpParams(); params.setParameter("http.protocol.handle-redirects", false); request.setParams(params); HttpResponse response = httpClient.execute(request); StatusLine statusLine = response.getStatusLine(); int status = statusLine.getStatusCode(); if (status == HttpStatus.SC_MOVED_PERMANENTLY || status == HttpStatus.SC_MOVED_TEMPORARILY) { Header target = response.getFirstHeader("location"); if (target != null && target.getValue() != null && target.getValue().endsWith("/")) return true; } return false; } catch (Exception e) { LogUtils.warning(e, "Unable to check if %s is folder: %s", uri.toString(), e.getMessage()); return false; } } return false; }
From source file:com.github.ignition.support.http.IgnitedHttpClient.java
public void updateProxySettings() { if (appContext == null) { return;/* w ww .j ava2 s . c o m*/ } HttpParams httpParams = httpClient.getParams(); ConnectivityManager connectivity = (ConnectivityManager) appContext .getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo nwInfo = connectivity.getActiveNetworkInfo(); if (nwInfo == null) { return; } Log.i(LOG_TAG, nwInfo.toString()); if (nwInfo.getType() == ConnectivityManager.TYPE_MOBILE) { String proxyHost = Proxy.getHost(appContext); if (proxyHost == null) { proxyHost = Proxy.getDefaultHost(); } int proxyPort = Proxy.getPort(appContext); if (proxyPort == -1) { proxyPort = Proxy.getDefaultPort(); } if (proxyHost != null && proxyPort > -1) { HttpHost proxy = new HttpHost(proxyHost, proxyPort); httpParams.setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy); } else { httpParams.setParameter(ConnRoutePNames.DEFAULT_PROXY, null); } } else { httpParams.setParameter(ConnRoutePNames.DEFAULT_PROXY, null); } }
From source file:com.vdisk.net.session.AbstractSession.java
/** * {@inheritDoc} <br/>// w w w . ja v a 2 s . c o m * <br/> * The default implementation does all of this and more, including using a * connection pool and killing connections after a timeout to use less * battery power on mobile devices. It's unlikely that you'll want to change * this behavior. */ @Override public synchronized HttpClient getHttpClient() { if (client == null) { // Set up default connection params. There are two routes to // VDisk - api server and content server. HttpParams connParams = new BasicHttpParams(); ConnManagerParams.setMaxConnectionsPerRoute(connParams, new ConnPerRoute() { @Override public int getMaxForRoute(HttpRoute route) { return 10; } }); ConnManagerParams.setMaxTotalConnections(connParams, 20); // Set up scheme registry. SchemeRegistry schemeRegistry = new SchemeRegistry(); schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80)); try { schemeRegistry.register(new Scheme("https", TrustAllSSLSocketFactory.getDefault(), 443)); } catch (Exception e) { } DBClientConnManager cm = new DBClientConnManager(connParams, schemeRegistry); // Set up client params. HttpParams httpParams = new BasicHttpParams(); HttpConnectionParams.setConnectionTimeout(httpParams, DEFAULT_TIMEOUT_MILLIS); HttpConnectionParams.setSoTimeout(httpParams, DEFAULT_TIMEOUT_MILLIS); HttpConnectionParams.setSocketBufferSize(httpParams, 8192); HttpProtocolParams.setUserAgent(httpParams, makeUserAgent()); httpParams.setParameter(ClientPNames.HANDLE_REDIRECTS, false); DefaultHttpClient c = new DefaultHttpClient(cm, httpParams) { @Override protected ConnectionKeepAliveStrategy createConnectionKeepAliveStrategy() { return new DBKeepAliveStrategy(); } @Override protected ConnectionReuseStrategy createConnectionReuseStrategy() { return new DBConnectionReuseStrategy(); } }; c.addRequestInterceptor(new HttpRequestInterceptor() { @Override public void process(final HttpRequest request, final HttpContext context) throws HttpException, IOException { if (!request.containsHeader("Accept-Encoding")) { request.addHeader("Accept-Encoding", "gzip"); } } }); c.addResponseInterceptor(new HttpResponseInterceptor() { @Override 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 (HeaderElement codec : codecs) { if (codec.getName().equalsIgnoreCase("gzip")) { response.setEntity(new GzipDecompressingEntity(response.getEntity())); return; } } } } } }); c.setHttpRequestRetryHandler(new RetryHandler(DEFAULT_MAX_RETRIES)); client = c; } return client; }
From source file:org.dasein.cloud.tier3.APIHandler.java
private @Nonnull HttpClient getClient(URI uri) throws InternalException, CloudException { ProviderContext ctx = provider.getContext(); if (ctx == null) { throw new NoContextException(); }/* w ww .ja v a 2s.c o m*/ boolean ssl = uri.getScheme().startsWith("https"); HttpParams params = new BasicHttpParams(); HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); // noinspection deprecation HttpProtocolParams.setContentCharset(params, Consts.UTF_8.toString()); HttpProtocolParams.setUserAgent(params, "Dasein Cloud"); params.setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 10000); params.setParameter(CoreConnectionPNames.SO_TIMEOUT, 300000); Properties p = ctx.getCustomProperties(); if (p != null) { String proxyHost = p.getProperty("proxyHost"); String proxyPort = p.getProperty("proxyPort"); if (proxyHost != null) { int port = 0; if (proxyPort != null && proxyPort.length() > 0) { port = Integer.parseInt(proxyPort); } params.setParameter(ConnRoutePNames.DEFAULT_PROXY, new HttpHost(proxyHost, port, ssl ? "https" : "http")); } } return new DefaultHttpClient(); }
From source file:org.dasein.cloud.cloudstack.CSMethod.java
protected @Nonnull HttpClient getClient(String url) throws InternalException { ProviderContext ctx = provider.getContext(); if (ctx == null) { throw new InternalException("No context was specified for this request"); }/* w w w. j av a 2s . c o m*/ boolean ssl = url.startsWith("https"); HttpParams params = new BasicHttpParams(); HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); //noinspection deprecation HttpProtocolParams.setContentCharset(params, HTTP.UTF_8); HttpProtocolParams.setUserAgent(params, "Dasein Cloud"); Properties p = ctx.getCustomProperties(); if (p != null) { String proxyHost = p.getProperty("proxyHost"); String proxyPort = p.getProperty("proxyPort"); if (proxyHost != null) { int port = 0; if (proxyPort != null && proxyPort.length() > 0) { port = Integer.parseInt(proxyPort); } params.setParameter(ConnRoutePNames.DEFAULT_PROXY, new HttpHost(proxyHost, port, ssl ? "https" : "http")); } } return new DefaultHttpClient(params); }
From source file:org.dasein.cloud.skeleton.RESTMethod.java
private @Nonnull HttpClient getClient(URI uri) throws InternalException, CloudException { ProviderContext ctx = provider.getContext(); if (ctx == null) { throw new NoContextException(); }//from ww w . j ava2s.c o m boolean ssl = uri.getScheme().startsWith("https"); HttpParams params = new BasicHttpParams(); HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); //noinspection deprecation HttpProtocolParams.setContentCharset(params, HTTP.UTF_8); HttpProtocolParams.setUserAgent(params, "Dasein Cloud"); params.setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 10000); params.setParameter(CoreConnectionPNames.SO_TIMEOUT, 300000); Properties p = ctx.getCustomProperties(); if (p != null) { String proxyHost = p.getProperty("proxyHost"); String proxyPort = p.getProperty("proxyPort"); if (proxyHost != null) { int port = 0; if (proxyPort != null && proxyPort.length() > 0) { port = Integer.parseInt(proxyPort); } params.setParameter(ConnRoutePNames.DEFAULT_PROXY, new HttpHost(proxyHost, port, ssl ? "https" : "http")); } } return new DefaultHttpClient(params); }