use of org.apache.http.client.config.RequestConfig in project dropwizard by dropwizard.
the class HttpClientBuilder method createClient.
/**
* Map the parameters in {@link HttpClientConfiguration} to configuration on a
* {@link org.apache.http.impl.client.HttpClientBuilder} instance
*
* @param builder
* @param manager
* @param name
* @return the configured {@link CloseableHttpClient}
*/
protected ConfiguredCloseableHttpClient createClient(final org.apache.http.impl.client.HttpClientBuilder builder, final InstrumentedHttpClientConnectionManager manager, final String name) {
final String cookiePolicy = configuration.isCookiesEnabled() ? CookieSpecs.DEFAULT : CookieSpecs.IGNORE_COOKIES;
final Integer timeout = (int) configuration.getTimeout().toMilliseconds();
final Integer connectionTimeout = (int) configuration.getConnectionTimeout().toMilliseconds();
final Integer connectionRequestTimeout = (int) configuration.getConnectionRequestTimeout().toMilliseconds();
final long keepAlive = configuration.getKeepAlive().toMilliseconds();
final ConnectionReuseStrategy reuseStrategy = keepAlive == 0 ? new NoConnectionReuseStrategy() : new DefaultConnectionReuseStrategy();
final HttpRequestRetryHandler retryHandler = configuration.getRetries() == 0 ? NO_RETRIES : (httpRequestRetryHandler == null ? new DefaultHttpRequestRetryHandler(configuration.getRetries(), false) : httpRequestRetryHandler);
final RequestConfig requestConfig = RequestConfig.custom().setCookieSpec(cookiePolicy).setSocketTimeout(timeout).setConnectTimeout(connectionTimeout).setConnectionRequestTimeout(connectionRequestTimeout).build();
final SocketConfig socketConfig = SocketConfig.custom().setTcpNoDelay(true).setSoTimeout(timeout).build();
customizeBuilder(builder).setRequestExecutor(new InstrumentedHttpRequestExecutor(metricRegistry, metricNameStrategy, name)).setConnectionManager(manager).setDefaultRequestConfig(requestConfig).setDefaultSocketConfig(socketConfig).setConnectionReuseStrategy(reuseStrategy).setRetryHandler(retryHandler).setUserAgent(createUserAgent(name));
if (keepAlive != 0) {
// either keep alive based on response header Keep-Alive,
// or if the server can keep a persistent connection (-1), then override based on client's configuration
builder.setKeepAliveStrategy(new DefaultConnectionKeepAliveStrategy() {
@Override
public long getKeepAliveDuration(HttpResponse response, HttpContext context) {
final long duration = super.getKeepAliveDuration(response, context);
return (duration == -1) ? keepAlive : duration;
}
});
}
// create a tunnel through a proxy host if it's specified in the config
final ProxyConfiguration proxy = configuration.getProxyConfiguration();
if (proxy != null) {
final HttpHost httpHost = new HttpHost(proxy.getHost(), proxy.getPort(), proxy.getScheme());
builder.setRoutePlanner(new NonProxyListProxyRoutePlanner(httpHost, proxy.getNonProxyHosts()));
// if the proxy host requires authentication then add the host credentials to the credentials provider
final AuthConfiguration auth = proxy.getAuth();
if (auth != null) {
if (credentialsProvider == null) {
credentialsProvider = new BasicCredentialsProvider();
}
credentialsProvider.setCredentials(new AuthScope(httpHost), new UsernamePasswordCredentials(auth.getUsername(), auth.getPassword()));
}
}
if (credentialsProvider != null) {
builder.setDefaultCredentialsProvider(credentialsProvider);
}
if (routePlanner != null) {
builder.setRoutePlanner(routePlanner);
}
if (disableContentCompression) {
builder.disableContentCompression();
}
if (redirectStrategy != null) {
builder.setRedirectStrategy(redirectStrategy);
}
if (defaultHeaders != null) {
builder.setDefaultHeaders(defaultHeaders);
}
if (verifier != null) {
builder.setSSLHostnameVerifier(verifier);
}
if (httpProcessor != null) {
builder.setHttpProcessor(httpProcessor);
}
return new ConfiguredCloseableHttpClient(builder.build(), requestConfig);
}
use of org.apache.http.client.config.RequestConfig in project frontend-maven-plugin by eirslett.
the class DefaultFileDownloader method executeViaProxy.
private CloseableHttpResponse executeViaProxy(Proxy proxy, String requestUrl) throws IOException {
final CloseableHttpClient proxyClient;
if (proxy.useAuthentication()) {
proxyClient = buildHttpClient(makeCredentialsProvider(proxy.host, proxy.port, proxy.username, proxy.password));
} else {
proxyClient = buildHttpClient(null);
}
final HttpHost proxyHttpHost = new HttpHost(proxy.host, proxy.port);
final RequestConfig requestConfig = RequestConfig.custom().setProxy(proxyHttpHost).build();
final HttpGet request = new HttpGet(requestUrl);
request.setConfig(requestConfig);
return proxyClient.execute(request);
}
use of org.apache.http.client.config.RequestConfig in project moco by dreamhead.
the class AbstractProxyResponseHandler method prepareRemoteRequest.
private HttpRequestBase prepareRemoteRequest(final FullHttpRequest request, final URL url) {
HttpRequestBase remoteRequest = createRemoteRequest(request, url);
RequestConfig config = RequestConfig.custom().setRedirectsEnabled(false).build();
remoteRequest.setConfig(config);
remoteRequest.setProtocolVersion(createVersion(request));
long contentLength = HttpUtil.getContentLength(request, -1);
if (contentLength > 0 && remoteRequest instanceof HttpEntityEnclosingRequest) {
HttpEntityEnclosingRequest entityRequest = (HttpEntityEnclosingRequest) remoteRequest;
entityRequest.setEntity(createEntity(request.content(), contentLength));
}
return remoteRequest;
}
use of org.apache.http.client.config.RequestConfig in project elasticsearch-analysis-ik by medcl.
the class Monitor method run.
/**
* 监控流程:
* ①向词库服务器发送Head请求
* ②从响应中获取Last-Modify、ETags字段值,判断是否变化
* ③如果未变化,休眠1min,返回第①步
* ④如果有变化,重新加载词典
* ⑤休眠1min,返回第①步
*/
public void run() {
//超时设置
RequestConfig rc = RequestConfig.custom().setConnectionRequestTimeout(10 * 1000).setConnectTimeout(10 * 1000).setSocketTimeout(15 * 1000).build();
HttpHead head = new HttpHead(location);
head.setConfig(rc);
//设置请求头
if (last_modified != null) {
head.setHeader("If-Modified-Since", last_modified);
}
if (eTags != null) {
head.setHeader("If-None-Match", eTags);
}
CloseableHttpResponse response = null;
try {
response = httpclient.execute(head);
//返回200 才做操作
if (response.getStatusLine().getStatusCode() == 200) {
if (((response.getLastHeader("Last-Modified") != null) && !response.getLastHeader("Last-Modified").getValue().equalsIgnoreCase(last_modified)) || ((response.getLastHeader("ETag") != null) && !response.getLastHeader("ETag").getValue().equalsIgnoreCase(eTags))) {
// 远程词库有更新,需要重新加载词典,并修改last_modified,eTags
Dictionary.getSingleton().reLoadMainDict();
last_modified = response.getLastHeader("Last-Modified") == null ? null : response.getLastHeader("Last-Modified").getValue();
eTags = response.getLastHeader("ETag") == null ? null : response.getLastHeader("ETag").getValue();
}
} else if (response.getStatusLine().getStatusCode() == 304) {
//没有修改,不做操作
//noop
} else {
logger.info("remote_ext_dict {} return bad code {}", location, response.getStatusLine().getStatusCode());
}
} catch (Exception e) {
logger.error("remote_ext_dict {} error!", e, location);
} finally {
try {
if (response != null) {
response.close();
}
} catch (IOException e) {
logger.error(e.getMessage(), e);
}
}
}
use of org.apache.http.client.config.RequestConfig in project weixin-java-tools by chanjarster.
the class WxMpServiceImpl method getJSSDKPayResult.
@Override
public WxMpPayResult getJSSDKPayResult(String transactionId, String outTradeNo) {
String nonce_str = System.currentTimeMillis() + "";
SortedMap<String, String> packageParams = new TreeMap<String, String>();
packageParams.put("appid", wxMpConfigStorage.getAppId());
packageParams.put("mch_id", wxMpConfigStorage.getPartnerId());
if (transactionId != null && !"".equals(transactionId.trim()))
packageParams.put("transaction_id", transactionId);
else if (outTradeNo != null && !"".equals(outTradeNo.trim()))
packageParams.put("out_trade_no", outTradeNo);
else
throw new IllegalArgumentException("Either 'transactionId' or 'outTradeNo' must be given.");
packageParams.put("nonce_str", nonce_str);
packageParams.put("sign", WxCryptUtil.createSign(packageParams, wxMpConfigStorage.getPartnerKey()));
StringBuilder request = new StringBuilder("<xml>");
for (Entry<String, String> para : packageParams.entrySet()) {
request.append(String.format("<%s>%s</%s>", para.getKey(), para.getValue(), para.getKey()));
}
request.append("</xml>");
HttpPost httpPost = new HttpPost("https://api.mch.weixin.qq.com/pay/orderquery");
if (httpProxy != null) {
RequestConfig config = RequestConfig.custom().setProxy(httpProxy).build();
httpPost.setConfig(config);
}
StringEntity entity = new StringEntity(request.toString(), Consts.UTF_8);
httpPost.setEntity(entity);
try {
CloseableHttpResponse response = httpClient.execute(httpPost);
String responseContent = Utf8ResponseHandler.INSTANCE.handleResponse(response);
XStream xstream = XStreamInitializer.getInstance();
xstream.alias("xml", WxMpPayResult.class);
WxMpPayResult wxMpPayResult = (WxMpPayResult) xstream.fromXML(responseContent);
return wxMpPayResult;
} catch (IOException e) {
throw new RuntimeException("Failed to query order due to IO exception.", e);
}
}
Aggregations