List of usage examples for org.apache.http.params HttpParams setBooleanParameter
HttpParams setBooleanParameter(String str, boolean z);
From source file:jsonbroker.library.client.http.HttpDispatcher.java
public HttpDispatcher(NetworkAddress networkAddress) { _networkAddress = networkAddress;/* w w w .java2s . c o m*/ /* with ... _client = new DefaultHttpClient(); ... we get the following error ... "Invalid use of SingleClientConnManager: connection still allocated.\nMake sure to release the connection before allocating another one." ... using a thread safe connecion manager ... * http://hc.apache.org/httpcomponents-client-ga/tutorial/html/connmgmt.html * http://thinkandroid.wordpress.com/2009/12/31/creating-an-http-client-example/ */ //sets up parameters HttpParams params = new BasicHttpParams(); HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); HttpProtocolParams.setContentCharset(params, "utf-8"); params.setBooleanParameter("http.protocol.expect-continue", false); // timeouts ... HttpConnectionParams.setConnectionTimeout(params, 5 * 1000); HttpConnectionParams.setSoTimeout(params, 5 * 1000); //registers schemes for both http and https SchemeRegistry registry = new SchemeRegistry(); registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80)); final SSLSocketFactory sslSocketFactory = SSLSocketFactory.getSocketFactory(); sslSocketFactory.setHostnameVerifier(SSLSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER); registry.register(new Scheme("https", sslSocketFactory, 443)); ThreadSafeClientConnManager manager = new ThreadSafeClientConnManager(params, registry); _client = new DefaultHttpClient(manager, params); }
From source file:org.onehippo.cms7.brokenlinks.LinkChecker.java
public LinkChecker(CheckExternalBrokenLinksConfig config, Session session) { this.session = session; ClientConnectionManager connManager = new PoolingClientConnectionManager(); HttpParams params = new SyncBasicHttpParams(); params.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, config.getSocketTimeout()); params.setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, config.getConnectionTimeout()); params.setBooleanParameter(CoreConnectionPNames.STALE_CONNECTION_CHECK, false); params.setBooleanParameter(ClientPNames.HANDLE_AUTHENTICATION, false); HttpClient client = null;//from www .j a v a 2 s . c o m try { final String httpClientClassName = config.getHttpClientClassName(); Class<? extends HttpClient> clientClass = (Class<? extends HttpClient>) Class .forName(httpClientClassName); final Constructor<? extends HttpClient> constructor = clientClass .getConstructor(ClientConnectionManager.class, HttpParams.class); client = constructor.newInstance(connManager, params); } catch (ClassNotFoundException e) { log.error("Could not find configured http client class", e); } catch (NoSuchMethodException e) { log.error("Could not find constructor of signature <init>(ClientConnectionmanager, HttpParams)", e); } catch (InvocationTargetException e) { log.error("Could not invoke constructor of httpClient", e); } catch (InstantiationException e) { log.error("Could not instantiate http client", e); } catch (IllegalAccessException e) { log.error("Not allowed to access http client constructor", e); } if (client == null) { client = new DefaultHttpClient(connManager, params); } httpClient = client; nrOfThreads = config.getNrOfHttpThreads(); // authentication preemptive true // allow circular redirects true }
From source file:eu.nullbyte.android.urllib.Urllib.java
public Urllib(Context context, ClientCertificate clientCert, Certificate[] pins) { mContext = context;/* w w w .jav a 2 s.co m*/ this.headers = new HashMap<String, String>(); userAgent = createUserAgentString(); HttpParams params = new BasicHttpParams(); HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); HttpProtocolParams.setContentCharset(params, this.charset); params.setBooleanParameter("http.protocol.expect-continue", false); SchemeRegistry registry = new SchemeRegistry(); registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80)); SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context); boolean trustSystemKeystore = prefs.getBoolean("debug_mode", false) && prefs.getBoolean("no_cert_pinning", false); try { mSSLSocketFactory = new CertPinningSSLSocketFactory(clientCert, pins); registry.register(new Scheme("https", pins != null && !trustSystemKeystore ? mSSLSocketFactory : SSLSocketFactory.getSocketFactory(), 443)); } catch (UnrecoverableKeyException e) { e.printStackTrace(); } catch (KeyManagementException e) { e.printStackTrace(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (KeyStoreException e) { e.printStackTrace(); } ClientConnectionManager manager = new ThreadSafeClientConnManager(params, registry); httpclient = new BankdroidHttpClient(manager, params); mHttpContext = new BasicHttpContext(); }
From source file:org.opengeoportal.proxy.controllers.OldDynamicOgcController.java
/** * An HTTP reverse proxy/gateway servlet. It is designed to be extended for customization * if desired. Most of the work is handled by * <a href="http://hc.apache.org/httpcomponents-client-ga/">Apache HttpClient</a>. * <p>//from w ww.j a v a 2s .com * There are alternatives to a servlet based proxy such as Apache mod_proxy if that is available to you. However * this servlet is easily customizable by Java, secure-able by your web application's security (e.g. spring-security), * portable across servlet engines, and is embeddable into another web application. * </p> * <p> * Inspiration: http://httpd.apache.org/docs/2.0/mod/mod_proxy.html * </p> * * @author David Smiley dsmiley@mitre.org> */ OldDynamicOgcController() { HttpParams hcParams = new BasicHttpParams(); hcParams.setBooleanParameter(ClientPNames.HANDLE_REDIRECTS, true); proxyClient = createHttpClient(hcParams); // Create a factory factory = DocumentBuilderFactory.newInstance(); //ignore validation, dtd factory.setAttribute("http://apache.org/xml/features/nonvalidating/load-external-dtd", false); factory.setValidating(false); transformerFactory = TransformerFactory.newInstance(); }
From source file:uk.co.tfd.sm.proxy.ProxyClientServiceImpl.java
/** * Executes a HTTP call using a path in the JCR to point to a template and a * map of properties to populate that template with. An example might be a * SOAP call.//from w w w. j a va 2s. c o m * * <pre> * {http://www.w3.org/2001/12/soap-envelope}Envelope:{ * {http://www.w3.org/2001/12/soap-envelope}Body:{ * {http://www.example.org/stock}GetStockPriceResponse:{ * >body:[ ] * {http://www.example.org/stock}Price:{ * >body:[34.5] * } * } * >body:[ ] * } * >body:[ ] * {http://www.w3.org/2001/12/soap-envelope}encodingStyle:[http://www.w3.org/2001/12/soap-encoding] * } * * </pre> * * @param resource * the resource containing the proxy end point specification. * @param headers * a map of headers to set int the request. * @param input * a map of parameters for all templates (both url and body) * @param requestInputStream * containing the request body (can be null if the call requires * no body or the template will be used to generate the body) * @param requestContentLength * if the requestImputStream is specified, the length specifies * the lenght of the body. * @param requerstContentType * the content type of the request, if null the node property * sakai:proxy-request-content-type will be used. * @throws ProxyClientException */ public ProxyResponse executeCall(Map<String, Object> config, Map<String, Object> headers, Map<String, Object> input, InputStream requestInputStream, long requestContentLength, String requestContentType) throws ProxyClientException { try { LOGGER.info( "Calling Execute Call with Config:[{}] Headers:[{}] Input:[{}] " + "RequestInputStream:[{}] InputStreamContentLength:[{}] RequestContentType:[{}] ", new Object[] { config, headers, input, requestInputStream, requestContentLength, requestContentType }); bindConfig(config); if (config != null && config.containsKey(CONFIG_REQUEST_PROXY_ENDPOINT)) { // setup the post request String endpointURL = (String) config.get(CONFIG_REQUEST_PROXY_ENDPOINT); if (isUnsafeProxyDefinition(config)) { try { URL u = new URL(endpointURL); String host = u.getHost(); if (host.indexOf('$') >= 0) { throw new ProxyClientException( "Invalid Endpoint template, relies on request to resolve valid URL " + u); } } catch (MalformedURLException e) { throw new ProxyClientException( "Invalid Endpoint template, relies on request to resolve valid URL", e); } } LOGGER.info("Valied Endpoint Def"); Map<String, Object> context = Maps.newHashMap(input); // add in the config properties from the bundle overwriting // everything else. context.put("config", configProperties); endpointURL = processUrlTemplate(endpointURL, context); LOGGER.info("Calling URL {} ", endpointURL); ProxyMethod proxyMethod = ProxyMethod.GET; if (config.containsKey(CONFIG_REQUEST_PROXY_METHOD)) { try { proxyMethod = ProxyMethod.valueOf((String) config.get(CONFIG_REQUEST_PROXY_METHOD)); } catch (Exception e) { } } HttpClient client = getHttpClient(); HttpUriRequest method = null; switch (proxyMethod) { case GET: if (config.containsKey(CONFIG_LIMIT_GET_SIZE)) { long maxSize = (Long) config.get(CONFIG_LIMIT_GET_SIZE); HttpHead h = new HttpHead(endpointURL); HttpParams params = h.getParams(); // make certain we reject the body of a head params.setBooleanParameter("http.protocol.reject-head-body", true); h.setParams(params); populateMessage(method, config, headers); HttpResponse response = client.execute(h); if (response.getStatusLine().getStatusCode() == 200) { // Check if the content-length is smaller than the // maximum (if any). Header contentLengthHeader = response.getLastHeader("Content-Length"); if (contentLengthHeader != null) { long length = Long.parseLong(contentLengthHeader.getValue()); if (length > maxSize) { return new ProxyResponseImpl(HttpServletResponse.SC_PRECONDITION_FAILED, "Response too large", response); } } } else { return new ProxyResponseImpl(response); } } method = new HttpGet(endpointURL); break; case HEAD: method = new HttpHead(endpointURL); break; case OPTIONS: method = new HttpOptions(endpointURL); break; case POST: method = new HttpPost(endpointURL); break; case PUT: method = new HttpPut(endpointURL); break; default: method = new HttpGet(endpointURL); } populateMessage(method, config, headers); if (requestInputStream == null && !config.containsKey(CONFIG_PROXY_REQUEST_TEMPLATE)) { if (method instanceof HttpPost) { HttpPost postMethod = (HttpPost) method; MultipartEntity multipart = new MultipartEntity(); for (Entry<String, Object> param : input.entrySet()) { String key = param.getKey(); Object value = param.getValue(); if (value instanceof Object[]) { for (Object val : (Object[]) value) { addPart(multipart, key, val); } } else { addPart(multipart, key, value); } postMethod.setEntity(multipart); } } } else { if (method instanceof HttpEntityEnclosingRequestBase) { String contentType = requestContentType; if (contentType == null && config.containsKey(CONFIG_REQUEST_CONTENT_TYPE)) { contentType = (String) config.get(CONFIG_REQUEST_CONTENT_TYPE); } if (contentType == null) { contentType = APPLICATION_OCTET_STREAM; } HttpEntityEnclosingRequestBase eemethod = (HttpEntityEnclosingRequestBase) method; if (requestInputStream != null) { eemethod.setHeader(HttpHeaders.CONTENT_TYPE, contentType); eemethod.setEntity(new InputStreamEntity(requestInputStream, requestContentLength)); } else { // build the request StringWriter body = new StringWriter(); templateService.evaluate(context, body, (String) config.get("path"), (String) config.get(CONFIG_PROXY_REQUEST_TEMPLATE)); byte[] soapBodyContent = body.toString().getBytes("UTF-8"); eemethod.setHeader(HttpHeaders.CONTENT_TYPE, contentType); eemethod.setEntity(new InputStreamEntity(new ByteArrayInputStream(soapBodyContent), soapBodyContent.length)); } } } HttpResponse response = client.execute(method); if (response.getStatusLine().getStatusCode() == 302 && method instanceof HttpEntityEnclosingRequestBase) { // handle redirects on post and put String url = response.getFirstHeader("Location").getValue(); method = new HttpGet(url); response = client.execute(method); } return new ProxyResponseImpl(response); } } catch (ProxyClientException e) { throw e; } catch (Exception e) { LOGGER.error(e.getMessage(), e); throw new ProxyClientException("The Proxy request specified by " + config + " failed, cause follows:", e); } finally { unbindConfig(); } throw new ProxyClientException( "The Proxy request specified by " + config + " does not contain a valid endpoint specification "); }
From source file:edu.cmu.cylab.starslinger.transaction.WebEngine.java
private byte[] doPost(String uri, byte[] requestBody) throws ExchangeException { mCancelable = false;/*from www. j a va 2 s .c o m*/ if (!SafeSlinger.getApplication().isOnline()) { throw new ExchangeException(mCtx.getString(R.string.error_CorrectYourInternetConnection)); } // sets up parameters HttpParams params = new BasicHttpParams(); HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); HttpProtocolParams.setContentCharset(params, "utf-8"); params.setBooleanParameter("http.protocol.expect-continue", false); if (mHttpClient == null) { mHttpClient = new CheckedHttpClient(params, mCtx); } HttpPost httppost = new HttpPost(uri); BasicResponseHandler responseHandler = new BasicResponseHandler(); byte[] reqData = null; HttpResponse response = null; long startTime = SystemClock.elapsedRealtime(); int statCode = 0; String statMsg = ""; String error = ""; try { // Execute HTTP Post Request httppost.addHeader("Content-Type", "application/octet-stream"); httppost.setEntity(new ByteArrayEntity(requestBody)); mTxTotalBytes = requestBody.length; final long totalTxBytes = TrafficStats.getTotalTxBytes(); final long totalRxBytes = TrafficStats.getTotalRxBytes(); if (totalTxBytes != TrafficStats.UNSUPPORTED) { mTxStartBytes = totalTxBytes; } if (totalRxBytes != TrafficStats.UNSUPPORTED) { mRxStartBytes = totalRxBytes; } response = mHttpClient.execute(httppost); reqData = responseHandler.handleResponse(response).getBytes("8859_1"); } catch (UnsupportedEncodingException e) { error = e.getLocalizedMessage() + " (" + e.getClass().getSimpleName() + ")"; } catch (HttpResponseException e) { // this subclass of java.io.IOException contains useful data for // users, do not swallow, handle properly statCode = e.getStatusCode(); statMsg = e.getLocalizedMessage(); error = (String.format(mCtx.getString(R.string.error_HttpCode), statCode) + ", \'" + statMsg + "\'"); } catch (java.io.IOException e) { // just show a simple Internet connection error, so as not to // confuse users error = mCtx.getString(R.string.error_CorrectYourInternetConnection); } catch (RuntimeException e) { error = e.getLocalizedMessage() + " (" + e.getClass().getSimpleName() + ")"; } catch (OutOfMemoryError e) { error = mCtx.getString(R.string.error_OutOfMemoryError); } finally { long msDelta = SystemClock.elapsedRealtime() - startTime; if (response != null) { StatusLine status = response.getStatusLine(); if (status != null) { statCode = status.getStatusCode(); statMsg = status.getReasonPhrase(); } } MyLog.d(TAG, uri + ", " + requestBody.length + "b sent, " + (reqData != null ? reqData.length : 0) + "b recv, " + statCode + " code, " + msDelta + "ms"); } if (!TextUtils.isEmpty(error) || reqData == null) { throw new ExchangeException(error); } return reqData; }
From source file:com.senseidb.dataprovider.http.HttpStreamDataProvider.java
public HttpStreamDataProvider(Comparator<String> versionComparator, String baseUrl, String pw, int fetchSize, String startingOffset, boolean disableHttps) { super(versionComparator); _baseUrl = baseUrl;// w ww .j av a 2 s . co m _password = pw; _fetchSize = fetchSize; _offset = startingOffset; _disableHttps = disableHttps; _initialOffset = null; _currentDataIter = null; _stopped = true; _httpGetLatency = 0L; _responseParseLatency = 0L; Scheme http = new Scheme("http", 80, PlainSocketFactory.getSocketFactory()); SchemeRegistry sr = new SchemeRegistry(); sr.register(http); HttpParams params = new BasicHttpParams(); params.setParameter(HttpProtocolParams.PROTOCOL_VERSION, HttpVersion.HTTP_1_1); params.setParameter(HttpProtocolParams.HTTP_CONTENT_CHARSET, "UTF-8"); params.setIntParameter(HttpConnectionParams.CONNECTION_TIMEOUT, 5000); // 5s conn timeout params.setIntParameter(HttpConnectionParams.SO_LINGER, 0); // no socket linger params.setBooleanParameter(HttpConnectionParams.TCP_NODELAY, true); // tcp no delay params.setIntParameter(HttpConnectionParams.SO_TIMEOUT, 5000); // 5s sock timeout params.setIntParameter(HttpConnectionParams.SOCKET_BUFFER_SIZE, 1024 * 1024); // 1mb socket buffer params.setBooleanParameter(HttpConnectionParams.SO_REUSEADDR, true); // 5s sock timeout _httpClientManager = new SingleClientConnManager(sr); _httpclient = new DefaultHttpClient(_httpClientManager, params); if (!_disableHttps) { _httpclient = HttpsClientDecorator.decorate(_httpclient); } _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(); 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; } } } } }); _retryTime = DEFAULT_RETRYTIME_MS; // default retry after 5 seconds }
From source file:com.neusou.bioroid.restful.RestfulClient.java
/** * Creates a <b>RestfulClient</b><br/><br/> * The intent actions will generated with the following rule: <br/><br/> * <the package name of the supplied context>.<the supplied name>.restful.<the action name> * /*from w ww .j a v a 2 s . c o m*/ * <br/><br/>Example: with context has package name com.neusou.facegraph and FB as the restful client name:<br/><br/> * com.neusou.facegraph.FB.restful.PROCESS_RESPONSE<br/> * com.neusou.facegraph.FB.restful.EXECUTE_REQUEST<br/> * com.neusou.facegraph.FB.restful.EXECUTE_REQUEST * <br/> * @param context context * @param name the unique name of the restful client */ public RestfulClient(Context context, String name) { if (name == null) { throw new IllegalArgumentException("name can not be null"); } if (context == null) { Logger.l(Logger.WARN, LOG_TAG, "Required Context argument is null."); } mContext = context; mName = name; HttpParams httpParams = new BasicHttpParams(); HttpProtocolParams.setVersion(httpParams, HttpVersion.HTTP_1_1); HttpProtocolParams.setContentCharset(httpParams, "UTF-8"); httpParams.setBooleanParameter("http.protocol.expect-continue", false); SchemeRegistry scheme = new SchemeRegistry(); scheme.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80)); final SSLSocketFactory sslSocketFactory = SSLSocketFactory.getSocketFactory(); sslSocketFactory.setHostnameVerifier(SSLSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER); scheme.register(new Scheme("https", sslSocketFactory, 443)); ThreadSafeClientConnManager tscm = new ThreadSafeClientConnManager(httpParams, scheme); httpClient = new DefaultHttpClient(tscm, httpParams); httpClient.setReuseStrategy(new ConnectionReuseStrategy() { @Override public boolean keepAlive(HttpResponse response, HttpContext context) { return false; } }); mExecutor.setRejectedExecutionHandler(new RejectedExecutionHandler() { @Override public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) { // Logger.l(Logger.DEBUG, LOG_TAG, "rejectedExecution. #activethread:"+executor.getActiveCount()+", queue.size:"+executor.getQueue().size()); } }); if (context != null) { setContext(context); } }
From source file:org.expath.httpclient.impl.ApacheHttpConnection.java
/** * Make a new Apache HTTP client, in order to serve this request. *//*from w w w.ja v a2 s . c o m*/ private AbstractHttpClient makeClient() { AbstractHttpClient client = new DefaultHttpClient(); HttpParams params = client.getParams(); // use the default JVM proxy settings (http.proxyHost, etc.) HttpRoutePlanner route = new ProxySelectorRoutePlanner(client.getConnectionManager().getSchemeRegistry(), ProxySelector.getDefault()); client.setRoutePlanner(route); // do follow redirections? params.setBooleanParameter(ClientPNames.HANDLE_REDIRECTS, myFollowRedirect); // set the timeout if any if (myTimeout != null) { // See http://blog.jayway.com/2009/03/17/configuring-timeout-with-apache-httpclient-40/ HttpConnectionParams.setConnectionTimeout(params, myTimeout * 1000); HttpConnectionParams.setSoTimeout(params, myTimeout * 1000); } // the shared cookie store client.setCookieStore(COOKIES); // the HTTP version (1.0 or 1.1) params.setParameter("http.protocol.version", myVersion); // return the just built client return client; }
From source file:org.apache.marmotta.ldclient.services.ldclient.LDClient.java
public LDClient(ClientConfiguration config) { log.info("Initialising Linked Data Client Service ..."); this.config = config; endpoints = new ArrayList<>(); for (Endpoint endpoint : defaultEndpoints) { endpoints.add(endpoint);//from w w w . j a v a2 s . c om } endpoints.addAll(config.getEndpoints()); Collections.sort(endpoints); if (log.isInfoEnabled()) { for (Endpoint endpoint : endpoints) { log.info("- LDClient Endpoint: {}", endpoint.getName()); } } providers = new ArrayList<>(); for (DataProvider provider : defaultProviders) { providers.add(provider); } providers.addAll(config.getProviders()); if (log.isInfoEnabled()) { for (DataProvider provider : providers) { log.info("- LDClient Provider: {}", provider.getName()); } } retrievalSemaphore = new Semaphore(config.getMaxParallelRequests()); if (config.getHttpClient() != null) { log.debug("Using HttpClient provided in the configuration"); this.client = config.getHttpClient(); } else { log.debug("Creating default HttpClient based on the configuration"); HttpParams httpParams = new BasicHttpParams(); httpParams.setParameter(CoreProtocolPNames.USER_AGENT, "Apache Marmotta LDClient"); httpParams.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, config.getSocketTimeout()); httpParams.setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, config.getConnectionTimeout()); httpParams.setBooleanParameter(ClientPNames.HANDLE_REDIRECTS, true); httpParams.setIntParameter(ClientPNames.MAX_REDIRECTS, 3); SchemeRegistry schemeRegistry = new SchemeRegistry(); schemeRegistry.register(new Scheme("http", 80, PlainSocketFactory.getSocketFactory())); try { SSLContext sslcontext = SSLContext.getInstance("TLS"); sslcontext.init(null, null, null); SSLSocketFactory sf = new SSLSocketFactory(sslcontext, SSLSocketFactory.STRICT_HOSTNAME_VERIFIER); schemeRegistry.register(new Scheme("https", 443, sf)); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (KeyManagementException e) { e.printStackTrace(); } PoolingClientConnectionManager cm = new PoolingClientConnectionManager(schemeRegistry); cm.setMaxTotal(20); cm.setDefaultMaxPerRoute(10); DefaultHttpClient client = new DefaultHttpClient(cm, httpParams); client.setRedirectStrategy(new LMFRedirectStrategy()); client.setHttpRequestRetryHandler(new LMFHttpRequestRetryHandler()); idleConnectionMonitorThread = new IdleConnectionMonitorThread(client.getConnectionManager()); idleConnectionMonitorThread.start(); this.client = client; } }