List of usage examples for org.apache.http.params HttpParams setParameter
HttpParams setParameter(String str, Object obj);
From source file:org.restlet.ext.httpclient.HttpClientHelper.java
/** * Configures the various parameters of the connection manager and the HTTP * client./*from ww w . j a v a2s.com*/ * * @param params * The parameter list to update. */ protected void configure(HttpParams params) { ConnManagerParams.setMaxTotalConnections(params, getMaxTotalConnections()); ConnManagerParams.setMaxConnectionsPerRoute(params, new ConnPerRouteBean(getMaxConnectionsPerHost())); // Configure other parameters HttpClientParams.setAuthenticating(params, false); HttpClientParams.setRedirecting(params, isFollowRedirects()); HttpClientParams.setCookiePolicy(params, "ignore"); HttpConnectionParams.setTcpNoDelay(params, getTcpNoDelay()); HttpConnectionParams.setConnectionTimeout(params, getSocketConnectTimeoutMs()); HttpConnectionParams.setSoTimeout(params, getSocketTimeout()); String httpProxyHost = getProxyHost(); if (httpProxyHost != null) { HttpHost proxy = new HttpHost(httpProxyHost, getProxyPort()); params.setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy); } }
From source file:ro.zg.netcell.connectors.HttpConnectionManager.java
private void initHttpClient() { ConfigurationData cfgData = dataSourceDefinition.getConfigData(); HttpParams params = new BasicHttpParams(); ConnManagerParams.setMaxTotalConnections(params, Integer .parseInt(cfgData.getParameterValue(DataSourceConfigParameters.MAX_TOTAL_CONNECTIONS).toString())); ConnPerRouteBean connPerRoute = new ConnPerRouteBean(10); HttpHost localhost = new HttpHost("locahost", 80); connPerRoute.setMaxForRoute(new HttpRoute(localhost), 50); ConnManagerParams.setMaxConnectionsPerRoute(params, connPerRoute); ConnManagerParams.setTimeout(params, Long .parseLong(cfgData.getParameterValue(DataSourceConfigParameters.CONNECTION_TIMEOUT).toString())); SchemeRegistry schemeRegistry = new SchemeRegistry(); schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80)); schemeRegistry.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443)); ClientConnectionManager cm = new ThreadSafeClientConnManager(params, schemeRegistry); /* set config params */ ConfigurationData configData = dataSourceDefinition.getConfigData(); Map<String, UserInputParameter> userInputParams = configData.getUserInputParams(); for (UserInputParameter uip : userInputParams.values()) { params.setParameter(uip.getInnerName(), uip.getValue()); }//w ww . j av a 2 s.c o m HttpConnectionParams.setSoTimeout(params, 25000); httpClient = new DefaultHttpClient(cm, params); }
From source file:se.kodapan.io.http.HttpAccessor.java
public synchronized void open() throws IOException { if (open) {// w w w . j a v a2s.c o m return; } if (temporaryContentFilePath == null) { temporaryContentFilePath = File.createTempFile(HttpAccessor.class.getSimpleName(), "contentFiles"); temporaryContentFilePath.delete(); } if (!temporaryContentFilePath.exists()) { if (!temporaryContentFilePath.mkdirs()) { throw new IOException("Could not create directory: " + temporaryContentFilePath.getAbsolutePath()); } } else if (!temporaryContentFilePath.isDirectory()) { throw new IOException("Not a directory: " + temporaryContentFilePath.getAbsolutePath()); } HttpParams params = new BasicHttpParams(); params.setIntParameter("http.socket.timeout", 10000); // 10 seconds params.setIntParameter("http.connection.timeout", 10000); // 10 seconds /* 'http.conn-manager.timeout': defines the timeout in milliseconds used when retrieving an instance of ManagedClientConnection from the ClientConnectionManager This parameter expects a value of type java.lang.Long. If this parameter is not set connection requests will not time out (infinite timeout). */ params.setLongParameter("http.conn-manager.timeout", 240000); // 4 minutes params.setIntParameter(ConnManagerPNames.MAX_TOTAL_CONNECTIONS, 50); params.setParameter(ConnManagerPNames.MAX_CONNECTIONS_PER_ROUTE, new ConnPerRoute() { @Override public int getMaxForRoute(HttpRoute httpRoute) { return 10; } }); SchemeRegistry registry = new SchemeRegistry(); registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80)); registry.register(new Scheme("https", org.apache.http.conn.ssl.SSLSocketFactory.getSocketFactory(), 443)); ThreadSafeClientConnManager connManager = new ThreadSafeClientConnManager(params, registry); httpClient = new DefaultHttpClient(connManager, params); // // http proxy! // // String proxyHost = "localhost"; // int proxyPort = 8123; // String proxyUsername = null; // String proxyPassword = null; // // final HttpHost hcProxyHost = new HttpHost(proxyHost, proxyPort, "http"); // httpClient.getCredentialsProvider().setCredentials( // new AuthScope(proxyHost, proxyPort), // new UsernamePasswordCredentials(proxyUsername, proxyPassword)); // httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, hcProxyHost); open = true; }
From source file:org.dasein.cloud.ibm.sce.SCEMethod.java
protected @Nonnull HttpClient getClient() throws InternalException { ProviderContext ctx = provider.getContext(); if (ctx == null) { throw new SCEConfigException("No context was defined for this request"); }/*from www. j a v a 2s.com*/ String endpoint = ctx.getEndpoint(); if (endpoint == null) { throw new SCEConfigException("No cloud endpoint was defined"); } boolean ssl = endpoint.startsWith("https"); int targetPort; URI uri; try { uri = new URI(endpoint); targetPort = uri.getPort(); if (targetPort < 1) { targetPort = (ssl ? 443 : 80); } } catch (URISyntaxException e) { throw new SCEConfigException(e); } HttpHost targetHost = new HttpHost(uri.getHost(), targetPort, uri.getScheme()); HttpParams params = new BasicHttpParams(); HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); //noinspection deprecation HttpProtocolParams.setContentCharset(params, HTTP.UTF_8); HttpProtocolParams.setUserAgent(params, ""); 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")); } } DefaultHttpClient client = new DefaultHttpClient(params); try { String userName = new String(ctx.getAccessPublic(), "utf-8"); String password = new String(ctx.getAccessPrivate(), "utf-8"); client.getCredentialsProvider().setCredentials( new AuthScope(targetHost.getHostName(), targetHost.getPort()), new UsernamePasswordCredentials(userName, password)); } catch (UnsupportedEncodingException e) { throw new InternalException(e); } return client; }
From source file:com.chen.emailsync.SyncManager.java
static public synchronized EmailClientConnectionManager getClientConnectionManager(Context context, HostAuth hostAuth) {// ww w. j a v a 2s. com // We'll use a different connection manager for each HostAuth EmailClientConnectionManager mgr = null; // We don't save managers for validation/autodiscover if (hostAuth.mId != HostAuth.NOT_SAVED) { mgr = sClientConnectionManagers.get(hostAuth.mId); } if (mgr == null) { // After two tries, kill the process. Most likely, this will happen in the background // The service will restart itself after about 5 seconds if (sClientConnectionManagerShutdownCount > MAX_CLIENT_CONNECTION_MANAGER_SHUTDOWNS) { alwaysLog("Shutting down process to unblock threads"); Process.killProcess(Process.myPid()); } HttpParams params = new BasicHttpParams(); params.setIntParameter(ConnManagerPNames.MAX_TOTAL_CONNECTIONS, 25); params.setParameter(ConnManagerPNames.MAX_CONNECTIONS_PER_ROUTE, sConnPerRoute); boolean ssl = hostAuth.shouldUseSsl(); int port = hostAuth.mPort; mgr = EmailClientConnectionManager.newInstance(context, params, hostAuth); log("Creating connection manager for port " + port + ", ssl: " + ssl); sClientConnectionManagers.put(hostAuth.mId, mgr); } // Null is a valid return result if we get an exception return mgr; }
From source file:com.googlecode.jsonrpc4j.JsonRpcHttpAsyncClient.java
private void initialize() { if (initialized.getAndSet(true)) { return;//from www . j a v a 2 s. co m } // HTTP parameters for the client final HttpParams params = new BasicHttpParams(); params.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, Integer.getInteger("com.googlecode.jsonrpc4j.async.socket.timeout", 30000)); params.setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, Integer.getInteger("com.googlecode.jsonrpc4j.async.connect.timeout", 30000)); params.setIntParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE, Integer.getInteger("com.googlecode.jsonrpc4j.async.socket.buffer", 8 * 1024)); params.setBooleanParameter(CoreConnectionPNames.TCP_NODELAY, Boolean.valueOf(System.getProperty("com.googlecode.jsonrpc4j.async.tcp.nodelay", "true"))); params.setParameter(CoreProtocolPNames.USER_AGENT, "jsonrpc4j/1.0"); // Create client-side I/O reactor final ConnectingIOReactor ioReactor; try { IOReactorConfig config = new IOReactorConfig(); config.setIoThreadCount(Integer.getInteger("com.googlecode.jsonrpc4j.async.reactor.threads", 1)); ioReactor = new DefaultConnectingIOReactor(config); } catch (IOReactorException e) { throw new RuntimeException("Exception initializing asynchronous Apache HTTP Client", e); } // Create a default SSLSetupHandler that accepts any certificate if (sslContext == null) { try { sslContext = SSLContext.getDefault(); } catch (Exception e) { throw new RuntimeException(e); } } // Create HTTP connection pool BasicNIOConnFactory nioConnFactory = new BasicNIOConnFactory(sslContext, null, params); pool = new BasicNIOConnPool(ioReactor, nioConnFactory, params); // Limit total number of connections to 500 by default pool.setDefaultMaxPerRoute(Integer.getInteger("com.googlecode.jsonrpc4j.async.max.inflight.route", 500)); pool.setMaxTotal(Integer.getInteger("com.googlecode.jsonrpc4j.async.max.inflight.total", 500)); // Run the I/O reactor in a separate thread Thread t = new Thread(new Runnable() { public void run() { try { // Create client-side HTTP protocol handler HttpAsyncRequestExecutor protocolHandler = new HttpAsyncRequestExecutor(); // Create client-side I/O event dispatch IOEventDispatch ioEventDispatch = new DefaultHttpClientIODispatch(protocolHandler, sslContext, params); // Ready to go! ioReactor.execute(ioEventDispatch); } catch (InterruptedIOException ex) { System.err.println("Interrupted"); } catch (IOException e) { System.err.println("I/O error: " + e.getMessage()); } } }, "jsonrpc4j HTTP IOReactor"); // Start the client thread t.setDaemon(true); t.start(); // Create HTTP protocol processing chain HttpProcessor httpproc = new ImmutableHttpProcessor(new HttpRequestInterceptor[] { // Use standard client-side protocol interceptors new RequestContent(), new RequestTargetHost(), new RequestConnControl(), new RequestUserAgent(), new RequestExpectContinue() }); // Create HTTP requester requester = new HttpAsyncRequester(httpproc, new DefaultConnectionReuseStrategy(), params); }
From source file:org.onebusaway.siri.core.SiriCommon.java
/**** * Setup Methods/*from www . j a v a 2s .c o m*/ ****/ @PostConstruct public void start() { HttpParams params = new BasicHttpParams(); /** * Override the default local address used for outgoing http client * connections, if specified */ if (_localAddress != null) { params.setParameter(ConnRoutePNames.LOCAL_ADDRESS, _localAddress); } /** * Set the timeout for both connections to a socket and for reading from a * socket. */ if (_connectionTimeout != 0) { HttpConnectionParams.setConnectionTimeout(params, _connectionTimeout * 1000); HttpConnectionParams.setSoTimeout(params, _connectionTimeout * 1000); } /** * We want to allow a fair-amount of concurrent connections. TODO: Can we * auto-tune this somehow? */ ConnManagerParams.setMaxTotalConnections(params, 50); /** * We want to create a connection manager that can pool multiple * connections. */ SchemeRegistry schemeRegistry = new SchemeRegistry(); schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80)); schemeRegistry.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443)); ClientConnectionManager connectionManager = new ThreadSafeClientConnManager(params, schemeRegistry); _client = new DefaultHttpClient(connectionManager, params); }
From source file:fi.laverca.util.CommonsHTTPSender.java
/** * invoke creates a socket connection, sends the request SOAP message and then * reads the response SOAP message back from the SOAP server * * @param msgContext the messsage context * * @throws AxisFault if there was an error sending the SOAP message *//*from ww w.java2s . c om*/ @Override public void invoke(final MessageContext msgContext) throws AxisFault { HttpPost post = null; HttpResponse response = null; if (log.isDebugEnabled()) { log.debug(Messages.getMessage("enter00", "CommonsHTTPSender::invoke")); } try { HttpClient httpClient = settings.get(); URL targetURL = new URL(msgContext.getStrProp(MessageContext.TRANS_URL)); Message reqMessage = msgContext.getRequestMessage(); post = new HttpPost(targetURL.toString()); // set false as default, addContentInfo can overwrite HttpParams params = post.getParams(); HttpProtocolParams.setUseExpectContinue(params, false); addContextInfo(post, httpClient, msgContext, targetURL); MessageRequestEntity requestEntity = null; if (msgContext.isPropertyTrue(HTTPConstants.MC_GZIP_REQUEST)) { requestEntity = new GzipMessageRequestEntity(post, reqMessage, httpChunkStream); } else { requestEntity = new MessageRequestEntity(post, reqMessage, httpChunkStream); } post.setEntity(requestEntity); String httpVersion = msgContext.getStrProp(MessageContext.HTTP_TRANSPORT_VERSION); if (httpVersion != null) { if (httpVersion.equals(HTTPConstants.HEADER_PROTOCOL_V10)) { params.setParameter(httpVersion, HttpVersion.HTTP_1_0); } } HttpContext localContext = new BasicHttpContext(); if (httpClient == null) { // We might end up here if initThreadLocals() was not properly called log.fatal("Initialization failed: No HTTPClient"); throw new AxisFault("Initialization failed: No HTTPClient"); } response = httpClient.execute(post, localContext); int returnCode = response.getStatusLine().getStatusCode(); String contentType = getHeader(post, HTTPConstants.HEADER_CONTENT_TYPE); String contentLocation = getHeader(post, HTTPConstants.HEADER_CONTENT_LOCATION); String contentLength = getHeader(post, HTTPConstants.HEADER_CONTENT_LENGTH); if ((returnCode > 199) && (returnCode < 300)) { // SOAP return is OK - so fall through } else if (msgContext.getSOAPConstants() == SOAPConstants.SOAP12_CONSTANTS) { // For now, if we're SOAP 1.2, fall through, since the range of // valid result codes is much greater } else if ((contentType != null) && !contentType.equals("text/html") && ((returnCode > 499) && (returnCode < 600))) { // SOAP Fault should be in here - so fall through } else { String statusMessage = response.getStatusLine().getReasonPhrase(); AxisFault fault = new AxisFault("HTTP", "(" + returnCode + ")" + statusMessage, null, null); try { String body = getResponseBodyAsString(response); fault.setFaultDetailString(Messages.getMessage("return01", "" + returnCode, body)); fault.addFaultDetail(Constants.QNAME_FAULTDETAIL_HTTPERRORCODE, Integer.toString(returnCode)); throw fault; } finally { HttpClientUtils.closeQuietly(response); post.releaseConnection(); } } // After this phase, the response and post are NOT to be closed/released // in this code path! See comments further below at "AXIS closure processing rules" // Wrap the response body stream so that close() also releases // the connection back to the pool. InputStream releaseConnectionOnCloseStream = createConnectionReleasingInputStream(post, response); Header contentEncoding = response.getFirstHeader(HTTPConstants.HEADER_CONTENT_ENCODING); if (contentEncoding != null) { if (contentEncoding.getValue().equalsIgnoreCase(HTTPConstants.COMPRESSION_GZIP)) { releaseConnectionOnCloseStream = new GZIPInputStream(releaseConnectionOnCloseStream); } else { try { releaseConnectionOnCloseStream.close(); } catch (Throwable t) { // ignore } throw new AxisFault("HTTP", "unsupported content-encoding of '" + contentEncoding.getValue() + "' found", null, null); } } Message outMsg = new Message(releaseConnectionOnCloseStream, false, contentType, contentLocation); // Transfer HTTP headers of HTTP message to MIME headers of SOAP message Header[] responseHeaders = post.getAllHeaders(); MimeHeaders responseMimeHeaders = outMsg.getMimeHeaders(); for (int i = 0; i < responseHeaders.length; i++) { Header responseHeader = responseHeaders[i]; responseMimeHeaders.addHeader(responseHeader.getName(), responseHeader.getValue()); } outMsg.setMessageType(Message.RESPONSE); msgContext.setResponseMessage(outMsg); if (log.isDebugEnabled()) { if (null == contentLength) { log.debug("\n" + Messages.getMessage("no00", "Content-Length")); } log.debug("\n" + Messages.getMessage("xmlRecd00")); log.debug("-----------------------------------------------"); log.debug(outMsg.getSOAPPartAsString()); } } catch (Exception e) { log.debug(e); throw AxisFault.makeFault(e); } finally { // AXIS closure processing rules.. // // 1: Always release the connection back to the pool // IF it was ONE WAY invocation if (msgContext.isPropertyTrue("axis.one.way")) { HttpClientUtils.closeQuietly(response); if (post != null) { post.releaseConnection(); } } else { log.debug("A HTTP POST which did NOT plan to release the HTTP connection back to the pool"); } // 2: Otherwise the Axis machinery will process call // close() on the releaseConnectionOnCloseStream. } if (log.isDebugEnabled()) { log.debug(Messages.getMessage("exit00", "CommonsHTTPSender::invoke")); } }
From source file:com.soundcloud.playerapi.ApiWrapper.java
/** * @return the default HttpParams//from ww w . j a v a 2 s . c o m * @see <a href="http://developer.android.com/reference/android/net/http/AndroidHttpClient.html#newInstance(java.lang.String, android.content.Context)"> * android.net.http.AndroidHttpClient#newInstance(String, Context)</a> */ protected HttpParams getParams() { final HttpParams params = new BasicHttpParams(); HttpConnectionParams.setConnectionTimeout(params, TIMEOUT); HttpConnectionParams.setSoTimeout(params, TIMEOUT); HttpConnectionParams.setSocketBufferSize(params, BUFFER_SIZE); ConnManagerParams.setMaxTotalConnections(params, MAX_TOTAL_CONNECTIONS); // Turn off stale checking. Our connections break all the time anyway, // and it's not worth it to pay the penalty of checking every time. HttpConnectionParams.setStaleCheckingEnabled(params, false); // fix contributed by Bjorn Roche XXX check if still needed params.setBooleanParameter("http.protocol.expect-continue", false); params.setParameter(ConnManagerPNames.MAX_CONNECTIONS_PER_ROUTE, new ConnPerRoute() { @Override public int getMaxForRoute(HttpRoute httpRoute) { if (env.isApiHost(httpRoute.getTargetHost())) { // there will be a lot of concurrent request to the API host return MAX_TOTAL_CONNECTIONS; } else { return ConnPerRouteBean.DEFAULT_MAX_CONNECTIONS_PER_ROUTE; } } }); // apply system proxy settings final String proxyHost = System.getProperty("http.proxyHost"); final String proxyPort = System.getProperty("http.proxyPort"); if (proxyHost != null) { int port = 80; try { port = Integer.parseInt(proxyPort); } catch (NumberFormatException ignored) { } params.setParameter(ConnRoutePNames.DEFAULT_PROXY, new HttpHost(proxyHost, port)); } return params; }
From source file:org.dasein.cloud.cloudsigma.CloudSigmaMethod.java
private @Nonnull HttpClient getClient(URI uri) throws InternalException, CloudException { ProviderContext ctx = provider.getContext(); if (ctx == null) { throw new NoContextException(); }/*from w ww . j a va 2 s . 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, ""); 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); }