Search in sources :

Example 51 with HttpClientContext

use of org.apache.http.client.protocol.HttpClientContext in project canal by alibaba.

the class HttpHelper method post0.

public String post0(String url, Map<String, String> heads, String requestBody, int timeout) {
    url = url.trim();
    HttpPost httpPost = null;
    CloseableHttpResponse response = null;
    try {
        URI uri = new URIBuilder(url).build();
        RequestConfig config = custom().setConnectTimeout(timeout).setConnectionRequestTimeout(timeout).setSocketTimeout(timeout).build();
        httpPost = new HttpPost(uri);
        StringEntity entity = new StringEntity(requestBody, "UTF-8");
        httpPost.setEntity(entity);
        httpPost.setHeader("Content-Type", "application/json;charset=utf8");
        if (heads != null) {
            for (Map.Entry<String, String> entry : heads.entrySet()) {
                httpPost.setHeader(entry.getKey(), entry.getValue());
            }
        }
        HttpClientContext context = HttpClientContext.create();
        context.setRequestConfig(config);
        response = httpclient.execute(httpPost, context);
        int statusCode = response.getStatusLine().getStatusCode();
        if (statusCode == HttpStatus.SC_OK) {
            return EntityUtils.toString(response.getEntity());
        } else {
            throw new RuntimeException("requestPost remote error, request : " + url + ", statusCode=" + statusCode + ";" + EntityUtils.toString(response.getEntity()));
        }
    } catch (Throwable t) {
        throw new RuntimeException("requestPost remote error, request : " + url, t);
    } finally {
        if (response != null) {
            try {
                response.close();
            } catch (IOException e) {
            // ignore
            }
        }
        if (httpPost != null) {
            httpPost.releaseConnection();
        }
    }
}
Also used : HttpPost(org.apache.http.client.methods.HttpPost) RequestConfig(org.apache.http.client.config.RequestConfig) HttpClientContext(org.apache.http.client.protocol.HttpClientContext) IOException(java.io.IOException) URI(java.net.URI) URIBuilder(org.apache.http.client.utils.URIBuilder) StringEntity(org.apache.http.entity.StringEntity) CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse) Map(java.util.Map)

Example 52 with HttpClientContext

use of org.apache.http.client.protocol.HttpClientContext in project canal by alibaba.

the class HttpHelper method getIgnoreCerf.

private static String getIgnoreCerf(String url, CookieStore cookieStore, Map<String, String> params, int timeout) {
    long start = System.currentTimeMillis();
    HttpClientBuilder builder = HttpClientBuilder.create();
    builder.setMaxConnPerRoute(50);
    builder.setMaxConnTotal(100);
    HttpGet httpGet = null;
    CloseableHttpResponse response = null;
    try {
        // 创建支持忽略证书的https
        final SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, (x509Certificates, s) -> true).build();
        CloseableHttpClient httpClient = HttpClientBuilder.create().setSSLContext(sslContext).setConnectionManager(new PoolingHttpClientConnectionManager(RegistryBuilder.<ConnectionSocketFactory>create().register("http", PlainConnectionSocketFactory.INSTANCE).register("https", new SSLConnectionSocketFactory(sslContext, NoopHostnameVerifier.INSTANCE)).build())).build();
        // ---------------- 创建支持https 的client成功---------
        URI uri = new URIBuilder(url).build();
        RequestConfig config = custom().setConnectTimeout(timeout).setConnectionRequestTimeout(timeout).setSocketTimeout(timeout).build();
        httpGet = new HttpGet(uri);
        HttpClientContext context = HttpClientContext.create();
        context.setRequestConfig(config);
        response = httpClient.execute(httpGet, context);
        int statusCode = response.getStatusLine().getStatusCode();
        if (statusCode == HttpStatus.SC_OK) {
            return EntityUtils.toString(response.getEntity());
        } else {
            String errorMsg = EntityUtils.toString(response.getEntity());
            throw new RuntimeException("requestGet remote error, url=" + uri.toString() + ", code=" + statusCode + ", error msg=" + errorMsg);
        }
    } catch (Throwable t) {
        long end = System.currentTimeMillis();
        long cost = end - start;
        String curlRequest = getCurlRequest(url, cookieStore, params, cost);
        throw new RuntimeException("requestPost(Https) remote error, request : " + curlRequest, t);
    } finally {
        long end = System.currentTimeMillis();
        long cost = end - start;
        printCurlRequest(url, null, null, cost);
        if (response != null) {
            try {
                response.close();
            } catch (IOException e) {
            }
        }
        if (httpGet != null) {
            httpGet.releaseConnection();
        }
    }
}
Also used : BasicNameValuePair(org.apache.http.message.BasicNameValuePair) HttpPost(org.apache.http.client.methods.HttpPost) SSLContext(javax.net.ssl.SSLContext) RegistryBuilder(org.apache.http.config.RegistryBuilder) UrlEncodedFormEntity(org.apache.http.client.entity.UrlEncodedFormEntity) HttpClientContext(org.apache.http.client.protocol.HttpClientContext) LoggerFactory(org.slf4j.LoggerFactory) HttpStatus(org.apache.http.HttpStatus) RequestConfig(org.apache.http.client.config.RequestConfig) EntityUtils(org.apache.http.util.EntityUtils) CookieStore(org.apache.http.client.CookieStore) Lists(com.google.common.collect.Lists) Charset(java.nio.charset.Charset) CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse) Map(java.util.Map) PlainConnectionSocketFactory(org.apache.http.conn.socket.PlainConnectionSocketFactory) PoolingHttpClientConnectionManager(org.apache.http.impl.conn.PoolingHttpClientConnectionManager) Cookie(org.apache.http.cookie.Cookie) URI(java.net.URI) NoopHostnameVerifier(org.apache.http.conn.ssl.NoopHostnameVerifier) SSLConnectionSocketFactory(org.apache.http.conn.ssl.SSLConnectionSocketFactory) CloseableHttpClient(org.apache.http.impl.client.CloseableHttpClient) Logger(org.slf4j.Logger) Iterator(java.util.Iterator) RequestConfig.custom(org.apache.http.client.config.RequestConfig.custom) URIBuilder(org.apache.http.client.utils.URIBuilder) IOException(java.io.IOException) SSLContextBuilder(org.apache.http.ssl.SSLContextBuilder) List(java.util.List) HttpGet(org.apache.http.client.methods.HttpGet) ConnectionSocketFactory(org.apache.http.conn.socket.ConnectionSocketFactory) HttpClientBuilder(org.apache.http.impl.client.HttpClientBuilder) NameValuePair(org.apache.http.NameValuePair) CloseableHttpClient(org.apache.http.impl.client.CloseableHttpClient) RequestConfig(org.apache.http.client.config.RequestConfig) HttpGet(org.apache.http.client.methods.HttpGet) HttpClientContext(org.apache.http.client.protocol.HttpClientContext) HttpClientBuilder(org.apache.http.impl.client.HttpClientBuilder) SSLContext(javax.net.ssl.SSLContext) IOException(java.io.IOException) SSLConnectionSocketFactory(org.apache.http.conn.ssl.SSLConnectionSocketFactory) URI(java.net.URI) PoolingHttpClientConnectionManager(org.apache.http.impl.conn.PoolingHttpClientConnectionManager) URIBuilder(org.apache.http.client.utils.URIBuilder) PlainConnectionSocketFactory(org.apache.http.conn.socket.PlainConnectionSocketFactory) SSLConnectionSocketFactory(org.apache.http.conn.ssl.SSLConnectionSocketFactory) ConnectionSocketFactory(org.apache.http.conn.socket.ConnectionSocketFactory) CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse) SSLContextBuilder(org.apache.http.ssl.SSLContextBuilder)

Example 53 with HttpClientContext

use of org.apache.http.client.protocol.HttpClientContext in project canal by alibaba.

the class HttpHelper method get.

public static String get(String url, int timeout) {
    // logger.info("get url is :" + url);
    // 支持采用https协议,忽略证书
    url = url.trim();
    if (url.startsWith("https")) {
        return getIgnoreCerf(url, null, null, timeout);
    }
    long start = System.currentTimeMillis();
    HttpClientBuilder builder = HttpClientBuilder.create();
    builder.setMaxConnPerRoute(50);
    builder.setMaxConnTotal(100);
    CloseableHttpClient httpclient = builder.build();
    CloseableHttpResponse response = null;
    HttpGet httpGet = null;
    try {
        URI uri = new URIBuilder(url).build();
        RequestConfig config = custom().setConnectTimeout(timeout).setConnectionRequestTimeout(timeout).setSocketTimeout(timeout).build();
        httpGet = new HttpGet(uri);
        HttpClientContext context = HttpClientContext.create();
        context.setRequestConfig(config);
        response = httpclient.execute(httpGet, context);
        int statusCode = response.getStatusLine().getStatusCode();
        if (statusCode == HttpStatus.SC_OK) {
            return EntityUtils.toString(response.getEntity());
        } else {
            String errorMsg = EntityUtils.toString(response.getEntity());
            throw new RuntimeException("requestGet remote error, url=" + uri.toString() + ", code=" + statusCode + ", error msg=" + errorMsg);
        }
    } catch (Throwable t) {
        long end = System.currentTimeMillis();
        long cost = end - start;
        String curlRequest = getCurlRequest(url, null, null, cost);
        throw new RuntimeException("requestGet remote error, request : " + curlRequest, t);
    } finally {
        long end = System.currentTimeMillis();
        long cost = end - start;
        printCurlRequest(url, null, null, cost);
        if (response != null) {
            try {
                response.close();
            } catch (IOException e) {
            }
        }
        httpGet.releaseConnection();
    }
}
Also used : CloseableHttpClient(org.apache.http.impl.client.CloseableHttpClient) RequestConfig(org.apache.http.client.config.RequestConfig) HttpGet(org.apache.http.client.methods.HttpGet) HttpClientContext(org.apache.http.client.protocol.HttpClientContext) HttpClientBuilder(org.apache.http.impl.client.HttpClientBuilder) IOException(java.io.IOException) URI(java.net.URI) URIBuilder(org.apache.http.client.utils.URIBuilder) CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse)

Example 54 with HttpClientContext

use of org.apache.http.client.protocol.HttpClientContext in project canal by alibaba.

the class HttpHelper method getBytes.

public static byte[] getBytes(String url, int timeout) throws Exception {
    long start = System.currentTimeMillis();
    HttpClientBuilder builder = HttpClientBuilder.create();
    builder.setMaxConnPerRoute(50);
    builder.setMaxConnTotal(100);
    CloseableHttpClient httpclient = builder.build();
    URI uri = new URIBuilder(url).build();
    RequestConfig config = custom().setConnectTimeout(timeout).setConnectionRequestTimeout(timeout).setSocketTimeout(timeout).build();
    HttpGet httpGet = new HttpGet(uri);
    HttpClientContext context = HttpClientContext.create();
    context.setRequestConfig(config);
    try (CloseableHttpResponse response = httpclient.execute(httpGet, context)) {
        int statusCode = response.getStatusLine().getStatusCode();
        long end = System.currentTimeMillis();
        long cost = end - start;
        if (logger.isWarnEnabled()) {
            logger.warn("post " + url + ", cost : " + cost);
        }
        if (statusCode == HttpStatus.SC_OK) {
            return EntityUtils.toByteArray(response.getEntity());
        } else {
            String errorMsg = EntityUtils.toString(response.getEntity());
            throw new RuntimeException("requestGet remote error, url=" + uri.toString() + ", code=" + statusCode + ", error msg=" + errorMsg);
        }
    } finally {
        httpGet.releaseConnection();
    }
}
Also used : CloseableHttpClient(org.apache.http.impl.client.CloseableHttpClient) RequestConfig(org.apache.http.client.config.RequestConfig) HttpGet(org.apache.http.client.methods.HttpGet) CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse) HttpClientContext(org.apache.http.client.protocol.HttpClientContext) HttpClientBuilder(org.apache.http.impl.client.HttpClientBuilder) URI(java.net.URI) URIBuilder(org.apache.http.client.utils.URIBuilder)

Example 55 with HttpClientContext

use of org.apache.http.client.protocol.HttpClientContext in project webmagic by code4craft.

the class HttpUriRequestConverter method convertHttpClientContext.

private HttpClientContext convertHttpClientContext(Request request, Site site, Proxy proxy) {
    HttpClientContext httpContext = new HttpClientContext();
    if (proxy != null && proxy.getUsername() != null) {
        AuthState authState = new AuthState();
        authState.update(new BasicScheme(ChallengeState.PROXY), new UsernamePasswordCredentials(proxy.getUsername(), proxy.getPassword()));
        httpContext.setAttribute(HttpClientContext.PROXY_AUTH_STATE, authState);
    }
    if (request.getCookies() != null && !request.getCookies().isEmpty()) {
        CookieStore cookieStore = new BasicCookieStore();
        for (Map.Entry<String, String> cookieEntry : request.getCookies().entrySet()) {
            BasicClientCookie cookie1 = new BasicClientCookie(cookieEntry.getKey(), cookieEntry.getValue());
            cookie1.setDomain(UrlUtils.removePort(UrlUtils.getDomain(request.getUrl())));
            cookieStore.addCookie(cookie1);
        }
        httpContext.setCookieStore(cookieStore);
    }
    return httpContext;
}
Also used : BasicScheme(org.apache.http.impl.auth.BasicScheme) CookieStore(org.apache.http.client.CookieStore) BasicCookieStore(org.apache.http.impl.client.BasicCookieStore) BasicCookieStore(org.apache.http.impl.client.BasicCookieStore) AuthState(org.apache.http.auth.AuthState) HttpClientContext(org.apache.http.client.protocol.HttpClientContext) BasicClientCookie(org.apache.http.impl.cookie.BasicClientCookie) Map(java.util.Map) UsernamePasswordCredentials(org.apache.http.auth.UsernamePasswordCredentials)

Aggregations

HttpClientContext (org.apache.http.client.protocol.HttpClientContext)160 HttpGet (org.apache.http.client.methods.HttpGet)56 CloseableHttpResponse (org.apache.http.client.methods.CloseableHttpResponse)54 IOException (java.io.IOException)48 HttpHost (org.apache.http.HttpHost)47 BasicCredentialsProvider (org.apache.http.impl.client.BasicCredentialsProvider)45 CloseableHttpClient (org.apache.http.impl.client.CloseableHttpClient)45 UsernamePasswordCredentials (org.apache.http.auth.UsernamePasswordCredentials)39 CredentialsProvider (org.apache.http.client.CredentialsProvider)39 URI (java.net.URI)32 HttpResponse (org.apache.http.HttpResponse)32 BasicScheme (org.apache.http.impl.auth.BasicScheme)32 BasicAuthCache (org.apache.http.impl.client.BasicAuthCache)32 AuthScope (org.apache.http.auth.AuthScope)31 AuthCache (org.apache.http.client.AuthCache)29 Test (org.junit.Test)29 HttpEntity (org.apache.http.HttpEntity)22 HttpClientBuilder (org.apache.http.impl.client.HttpClientBuilder)21 HttpClient (org.apache.http.client.HttpClient)18 RequestConfig (org.apache.http.client.config.RequestConfig)17