List of usage examples for org.apache.http.client.config RequestConfig custom
public static RequestConfig.Builder custom()
From source file:com.joken.notice.message.util.HttpRequestHandler.java
/** * ??post/*from ww w. j a v a2 s . c o m*/ * @Auther Hanzibin * @date 3:18:48 PM,Mar 11, 2016 * @return String */ public String sendPostRequest() { CloseableHttpResponse httpResponse = null; PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(); connManager.setMaxTotal(300); connManager.setDefaultMaxPerRoute(20); if (requestConfig == null) { requestConfig = RequestConfig.custom().setConnectionRequestTimeout(10000) .setStaleConnectionCheckEnabled(true).setConnectTimeout(10000).setSocketTimeout(10000).build(); } CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(connManager) .setDefaultRequestConfig(requestConfig).build(); HttpPost hp = new HttpPost(url); try { StringEntity entity = new StringEntity(postData, Charset.forName("UTF-8"));//? entity.setContentEncoding("UTF-8"); entity.setContentType("application/json"); hp.setEntity(entity); httpResponse = httpClient.execute(hp); return EntityUtils.toString(httpResponse.getEntity()); } catch (Throwable t) { t.printStackTrace(); log.info("??Http" + postData.toString() + ""); } finally { try { hp.releaseConnection(); } catch (Exception e) { } } return null; }
From source file:com.liferay.jenkins.tools.LocalStringGetter.java
@Override public String getString(String url) throws Exception { url = convertURL(url);/*from www . ja va 2 s .c o m*/ logger.debug("Fetching string from {}", url); RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(timeout).build(); HttpClient httpClient = HttpClientBuilder.create().setDefaultRequestConfig(requestConfig).build(); HttpResponse httpResponse = httpClient.execute(new HttpGet(url)); int statusCode = httpResponse.getStatusLine().getStatusCode(); logger.debug("Successfully fetched {}", url); return IOUtils.toString(httpResponse.getEntity().getContent(), Charset.defaultCharset()); }
From source file:org.jboss.pnc.client.ApacheHttpClient43EngineWithRetry.java
@Override protected HttpClient createDefaultHttpClient() { logger.info("Bootstrapping http engine with request retry handler..."); final HttpClientBuilder builder = HttpClientBuilder.create(); RequestConfig.Builder requestBuilder = RequestConfig.custom(); if (defaultProxy != null) { requestBuilder.setProxy(defaultProxy); }/*from w w w.j a v a 2s. c o m*/ builder.disableContentCompression(); builder.setDefaultRequestConfig(requestBuilder.build()); HttpRequestRetryHandler retryHandler = new StandardHttpRequestRetryHandler(); builder.setRetryHandler(retryHandler); return builder.build(); }
From source file:org.metaeffekt.dcc.agent.DccAgentEndpoint.java
public DccAgentEndpoint(String host, int port, int timeout) { this.host = host; this.port = port; this.requestConfig = RequestConfig.custom().setConnectionRequestTimeout(timeout).build(); }
From source file:tv.arte.resteventapi.core.clients.RestEventApiRestClient.java
/** * Executes the REST request described by the {@link RestEvent} * //ww w . j ava 2s . c om * @param restEvent The {@link RestEvent} to process * @return A result of the execution * @throws RestEventApiRuntimeException In case of non managed errors */ public static RestClientExecutionResult execute(final RestEvent restEvent) throws RestEventApiRuntimeException { RestClientExecutionResult result = new RestClientExecutionResult(); String url = restEvent.getUrl(); CloseableHttpClient client = null; HttpUriRequest request = null; Integer responseCode = null; try { //Request custom configs RequestConfig.Builder requestBuilder = RequestConfig.custom(); requestBuilder = requestBuilder.setConnectTimeout(restEvent.getTimeout()); requestBuilder = requestBuilder.setConnectionRequestTimeout(restEvent.getTimeout()); client = HttpClientBuilder.create().setDefaultRequestConfig(requestBuilder.build()).build(); //Determine the method to execute switch (restEvent.getMethod()) { case GET: request = new HttpGet(url); break; case POST: request = new HttpPost(url); break; case PUT: request = new HttpPut(url); break; case DELETE: request = new HttpDelete(url); break; case PATCH: request = new HttpPatch(url); break; case HEAD: request = new HttpHead(url); break; default: throw new RestEventApiRuntimeException("RestEventAPI unsupported HTTP method"); } //Set the body for eligible methods if (restEvent.getBody() != null && request instanceof HttpEntityEnclosingRequestBase) { ((HttpEntityEnclosingRequestBase) request).setEntity(new StringEntity(restEvent.getBody())); } //Set headers if (CollectionUtils.isNotEmpty(restEvent.getHeaders())) { for (String strHeader : restEvent.getHeaders()) { CharArrayBuffer headerBuffer = new CharArrayBuffer(strHeader.length() + 1); headerBuffer.append(strHeader); request.addHeader(new BufferedHeader(headerBuffer)); } } HttpResponse response = client.execute(request); responseCode = response.getStatusLine().getStatusCode(); result.setState(RestClientCallState.OK); } catch (ConnectTimeoutException e) { result.setState(RestClientCallState.TIMEOUT); } catch (Exception e) { throw new RestEventApiRuntimeException("Un error occured while processing rest event", e); } finally { result.setResponseCode(responseCode); try { client.close(); } catch (Exception e2) { logger.warn("Unable to close HTTP client", e2); } } return result; }
From source file:org.doxu.g2.gwc.crawler.Crawler.java
public void start() { String startUrl = "http://cache.trillinux.org/g2/bazooka.php"; session.addURL(startUrl);// www .j a va 2s. co m RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(Crawler.CONNECT_TIMEOUT) .setSocketTimeout(Crawler.CONNECT_TIMEOUT).build(); try (CloseableHttpClient httpClient = HttpClients.custom().setUserAgent("doxu/" + Crawler.VERSION) .setDefaultRequestConfig(requestConfig).disableAutomaticRetries().build()) { CrawlerThreadPoolExecutor executor = new CrawlerThreadPoolExecutor(GWC_CRAWLER_THREADS, GWC_CRAWLER_THREADS, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>()); executor.setListener(new IdleListener() { @Override public void idle() { // If the thread pool is idle and the queue of GWCs to crawl is empty // the crawl of GWCs is complete if (session.peek() == null) { crawlCompletedBarrier.countDown(); } } }); CrawlThreadFactory factory = CrawlThreadFactory.newFactory(session, httpClient); runQueueProcessor(factory, executor); executor.shutdown(); try { executor.awaitTermination(30, TimeUnit.SECONDS); } catch (InterruptedException ex) { Logger.getLogger(Crawler.class.getName()).log(Level.SEVERE, null, ex); } } catch (IOException ex) { Logger.getLogger(Crawler.class.getName()).log(Level.SEVERE, null, ex); } HostChecker hostChecker = new HostChecker(session); hostChecker.start(); printStats(); System.out.println(session.toXML()); }
From source file:kmi.taa.core.SPARQLHTTPClient.java
public String httpGet(String url, String proxy) throws ClientProtocolException, IOException { CloseableHttpClient httpclient = HttpClients.createDefault(); HttpGet httpget = new HttpGet(url); String responseBody;//from w ww . j a va 2 s .com try { if (!proxy.isEmpty()) { String[] str = proxy.split(":"); int port = Integer.parseInt(str[1]); HttpHost host = new HttpHost(str[0], port, str[2]); RequestConfig config = RequestConfig.custom().setProxy(host).build(); httpget.setConfig(config); } ResponseHandler<String> responseHandler = new ResponseHandler<String>() { public String handleResponse(final HttpResponse response) throws ClientProtocolException, IOException { int status = response.getStatusLine().getStatusCode(); if (status >= 200 && status < 300) { try { HttpEntity entity = response.getEntity(); return entity != null ? EntityUtils.toString(entity, StandardCharsets.UTF_8) : null; } catch (ClientProtocolException e) { return ""; } } return ""; } }; responseBody = httpclient.execute(httpget, responseHandler); } finally { httpclient.close(); } return responseBody; }
From source file:org.thoughtcrime.securesms.mms.IncomingMmsConnection.java
@Override protected HttpUriRequest constructRequest(boolean useProxy) throws IOException { HttpGetHC4 request = new HttpGetHC4(apn.getMmsc()); request.addHeader("Accept", "*/*, application/vnd.wap.mms-message, application/vnd.wap.sic"); if (useProxy) { HttpHost proxy = new HttpHost(apn.getProxy(), apn.getPort()); request.setConfig(RequestConfig.custom().setProxy(proxy).build()); }/*from www.j a v a2 s . c om*/ return request; }
From source file:securitytools.common.http.HttpClientFactory.java
public static CloseableHttpClient build(ClientConfiguration clientConfiguration) throws NoSuchAlgorithmException { HttpClientBuilder builder = HttpClients.custom(); // Certificate Validation if (clientConfiguration.isCertificateValidationEnabled()) { builder.setSSLSocketFactory(new SSLConnectionSocketFactory(SSLContext.getDefault(), SSLConnectionSocketFactory.STRICT_HOSTNAME_VERIFIER)); } else {//www. j a va 2 s . c o m // Disable builder.setSSLSocketFactory(new TrustingSSLConnectionSocketFactory()); } // Timeouts RequestConfig.Builder requestConfigBuilder = RequestConfig.custom(); requestConfigBuilder.setConnectTimeout(clientConfiguration.getConnectionTimeout()); requestConfigBuilder.setConnectionRequestTimeout(clientConfiguration.getConnectionTimeout()); requestConfigBuilder.setSocketTimeout(clientConfiguration.getSocketTimeout()); builder.setDefaultRequestConfig(requestConfigBuilder.build()); // User Agent builder.setUserAgent(clientConfiguration.getUserAgent()); // Proxy if (clientConfiguration.getProxyHost() != null) { builder.setProxy(clientConfiguration.getProxyHost()); } return builder.build(); }
From source file:com.smartling.api.sdk.util.HttpProxyUtils.java
/** * Get a request config given the applicable request and proxy config if any * @param httpRequest request/*from ww w . j a v a2s. c o m*/ * @param proxyConfiguration configuration of proxy to use * @return org.apache.http.client.config.RequestConfig */ public RequestConfig getProxyRequestConfig(HttpRequestBase httpRequest, final ProxyConfiguration proxyConfiguration) { if (hasActiveProxyConfiguration(proxyConfiguration)) { HttpHost proxyHttpHost = new HttpHost(proxyConfiguration.getHost(), proxyConfiguration.getPort()); return RequestConfig.custom().setProxy(proxyHttpHost).build(); } return null; }