Search in sources :

Example 51 with RequestConfig

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);
}
Also used : RequestConfig(org.apache.http.client.config.RequestConfig) BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) SocketConfig(org.apache.http.config.SocketConfig) NonProxyListProxyRoutePlanner(io.dropwizard.client.proxy.NonProxyListProxyRoutePlanner) DefaultConnectionReuseStrategy(org.apache.http.impl.DefaultConnectionReuseStrategy) DefaultHttpRequestRetryHandler(org.apache.http.impl.client.DefaultHttpRequestRetryHandler) HttpContext(org.apache.http.protocol.HttpContext) HttpResponse(org.apache.http.HttpResponse) AuthConfiguration(io.dropwizard.client.proxy.AuthConfiguration) InstrumentedHttpRequestExecutor(com.codahale.metrics.httpclient.InstrumentedHttpRequestExecutor) UsernamePasswordCredentials(org.apache.http.auth.UsernamePasswordCredentials) NoConnectionReuseStrategy(org.apache.http.impl.NoConnectionReuseStrategy) ProxyConfiguration(io.dropwizard.client.proxy.ProxyConfiguration) DefaultConnectionKeepAliveStrategy(org.apache.http.impl.client.DefaultConnectionKeepAliveStrategy) HttpHost(org.apache.http.HttpHost) AuthScope(org.apache.http.auth.AuthScope) NoConnectionReuseStrategy(org.apache.http.impl.NoConnectionReuseStrategy) DefaultConnectionReuseStrategy(org.apache.http.impl.DefaultConnectionReuseStrategy) ConnectionReuseStrategy(org.apache.http.ConnectionReuseStrategy) DefaultHttpRequestRetryHandler(org.apache.http.impl.client.DefaultHttpRequestRetryHandler) HttpRequestRetryHandler(org.apache.http.client.HttpRequestRetryHandler)

Example 52 with 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);
}
Also used : CloseableHttpClient(org.apache.http.impl.client.CloseableHttpClient) RequestConfig(org.apache.http.client.config.RequestConfig) HttpHost(org.apache.http.HttpHost) HttpGet(org.apache.http.client.methods.HttpGet)

Example 53 with RequestConfig

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;
}
Also used : RequestConfig(org.apache.http.client.config.RequestConfig) HttpRequestBase(org.apache.http.client.methods.HttpRequestBase) HttpEntityEnclosingRequest(org.apache.http.HttpEntityEnclosingRequest)

Example 54 with RequestConfig

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);
        }
    }
}
Also used : RequestConfig(org.apache.http.client.config.RequestConfig) CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse) IOException(java.io.IOException) HttpHead(org.apache.http.client.methods.HttpHead) IOException(java.io.IOException)

Example 55 with RequestConfig

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);
    }
}
Also used : HttpPost(org.apache.http.client.methods.HttpPost) RequestConfig(org.apache.http.client.config.RequestConfig) XStream(com.thoughtworks.xstream.XStream) IOException(java.io.IOException) TreeMap(java.util.TreeMap) WxMpPayResult(me.chanjar.weixin.mp.bean.result.WxMpPayResult) StringEntity(org.apache.http.entity.StringEntity) CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse)

Aggregations

RequestConfig (org.apache.http.client.config.RequestConfig)91 CloseableHttpClient (org.apache.http.impl.client.CloseableHttpClient)33 CloseableHttpResponse (org.apache.http.client.methods.CloseableHttpResponse)31 HttpGet (org.apache.http.client.methods.HttpGet)29 HttpPost (org.apache.http.client.methods.HttpPost)19 Test (org.junit.Test)16 IOException (java.io.IOException)14 StringEntity (org.apache.http.entity.StringEntity)14 WxErrorException (me.chanjar.weixin.common.exception.WxErrorException)13 HttpResponse (org.apache.http.HttpResponse)12 WxError (me.chanjar.weixin.common.bean.result.WxError)11 HttpEntity (org.apache.http.HttpEntity)11 URI (java.net.URI)10 PoolingHttpClientConnectionManager (org.apache.http.impl.conn.PoolingHttpClientConnectionManager)10 InputStream (java.io.InputStream)9 HttpHost (org.apache.http.HttpHost)9 HttpClientBuilder (org.apache.http.impl.client.HttpClientBuilder)9 Configurable (org.apache.http.client.methods.Configurable)7 BasicCredentialsProvider (org.apache.http.impl.client.BasicCredentialsProvider)7 Header (org.apache.http.Header)6