Search in sources :

Example 31 with RequestConfig

use of org.graylog.shaded.elasticsearch7.org.apache.http.client.config.RequestConfig in project pancm_project by xuwujing.

the class HttpClientUtil method post.

/**
 * post 请求
 *
 * @param postUrl    the post url
 * @param parameters the parameters
 * @return string
 * @throws Exception the exception
 */
public static String post(String postUrl, String parameters) throws Exception {
    CloseableHttpClient httpClient = null;
    HttpPost method = null;
    String body = null;
    try {
        httpClient = HttpClientBuilder.create().build();
        method = new HttpPost(postUrl);
        // 增加http请求超时设置
        RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(60000).setConnectionRequestTimeout(60000).setSocketTimeout(60000).build();
        method.setConfig(requestConfig);
        if (method != null && parameters != null) {
            logger.info("请求接口的url地址:{},请求参数:{}", postUrl, JSONObject.toJSONString(parameters));
            // 建立一个NameValuePair数组,用于存储欲传送的参数
            method.addHeader("Content-type", "application/json; charset=utf-8");
            method.setHeader("Accept", "application/json");
            method.setEntity(new StringEntity(parameters, Charset.forName("UTF-8")));
            HttpResponse response = httpClient.execute(method);
            int statusCode = response.getStatusLine().getStatusCode();
            // logger.debug("statusCode:" + statusCode);
            if (statusCode != HttpStatus.SC_OK) {
                logger.error("Method failed:" + response.getStatusLine());
                logger.error("Request:" + parameters);
                throw new Exception("statusCode:" + statusCode);
            }
            // Read the response body
            body = EntityUtils.toString(response.getEntity());
        }
    } catch (IOException e) {
        // 网络错误
        throw e;
    } finally {
        if (httpClient != null) {
            httpClient.close();
            httpClient = null;
            method = null;
        }
    // logger.debug("调用接口状态:" + status);
    }
    logger.info("接口返回参数:{}!", body);
    return body;
}
Also used : CloseableHttpClient(org.apache.http.impl.client.CloseableHttpClient) HttpPost(org.apache.http.client.methods.HttpPost) RequestConfig(org.apache.http.client.config.RequestConfig) StringEntity(org.apache.http.entity.StringEntity) HttpResponse(org.apache.http.HttpResponse) IOException(java.io.IOException) IOException(java.io.IOException)

Example 32 with RequestConfig

use of org.graylog.shaded.elasticsearch7.org.apache.http.client.config.RequestConfig in project coprhd-controller by CoprHD.

the class SSLHelper method getHttpClientBuilder.

/**
 * Generate a {@link HttpClientBuilder} instance to be used to create a httpclient instance.
 * @param threadSafeClients boolean if true a thread-safe HTTP client instance is created.
 * @param maxConnections for thread-safe clients, the maximum concurrent connections
 * @param maxConnectionsPerHost for thread-safe clients, the maximum concurrent connections allows to a specific host
 * @param useConnectionTimeout socket connection timeout in milliseconds
 * @param useConnectionReadTimeout connection read timeout in milliseconds
 * @param sslContext {@link SSLContext} initialized SSLContext instance
 * @return {@link HttpClientBuilder} instance
 */
private static HttpClientBuilder getHttpClientBuilder(boolean threadSafeClients, int maxConnections, int maxConnectionsPerHost, int useConnectionTimeout, int useConnectionReadTimeout, SSLContext sslContext) {
    SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory(sslContext, SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
    Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create().register(HTTP, PlainConnectionSocketFactory.getSocketFactory()).register(HTTPS, socketFactory).build();
    HttpClientConnectionManager cm = null;
    if (threadSafeClients) {
        cm = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
        if (maxConnections > 0) {
            ((PoolingHttpClientConnectionManager) cm).setMaxTotal(maxConnections);
        }
        if (maxConnectionsPerHost > 0) {
            ((PoolingHttpClientConnectionManager) cm).setDefaultMaxPerRoute(maxConnectionsPerHost);
        }
    } else {
        cm = new BasicHttpClientConnectionManager(socketFactoryRegistry);
    }
    // Build the request config identifying the socket connection parameters.
    RequestConfig.Builder requestConfigBulder = RequestConfig.custom();
    if (useConnectionReadTimeout > 0) {
        requestConfigBulder.setSocketTimeout(useConnectionReadTimeout);
    }
    if (useConnectionTimeout > 0) {
        requestConfigBulder.setConnectTimeout(useConnectionTimeout);
    }
    RequestConfig requestConfig = requestConfigBulder.setExpectContinueEnabled(true).build();
    // construct a client instance with the connection manager embedded
    HttpClientBuilder httpClientBuilder = HttpClients.custom();
    httpClientBuilder.setConnectionManager(cm);
    httpClientBuilder.setDefaultRequestConfig(requestConfig);
    return httpClientBuilder;
}
Also used : RequestConfig(org.apache.http.client.config.RequestConfig) ConnectionSocketFactory(org.apache.http.conn.socket.ConnectionSocketFactory) PlainConnectionSocketFactory(org.apache.http.conn.socket.PlainConnectionSocketFactory) SSLConnectionSocketFactory(org.apache.http.conn.ssl.SSLConnectionSocketFactory) HttpClientBuilder(org.apache.http.impl.client.HttpClientBuilder) HttpClientConnectionManager(org.apache.http.conn.HttpClientConnectionManager) BasicHttpClientConnectionManager(org.apache.http.impl.conn.BasicHttpClientConnectionManager) PoolingHttpClientConnectionManager(org.apache.http.impl.conn.PoolingHttpClientConnectionManager) SSLConnectionSocketFactory(org.apache.http.conn.ssl.SSLConnectionSocketFactory) BasicHttpClientConnectionManager(org.apache.http.impl.conn.BasicHttpClientConnectionManager) PoolingHttpClientConnectionManager(org.apache.http.impl.conn.PoolingHttpClientConnectionManager)

Example 33 with RequestConfig

use of org.graylog.shaded.elasticsearch7.org.apache.http.client.config.RequestConfig in project swift by luastar.

the class HttpClientUtils method getByte.

public static byte[] getByte(HttpParam param) {
    CloseableHttpClient httpclient = null;
    CloseableHttpResponse response = null;
    try {
        HttpGet httpGet = new HttpGet(param.getUrl());
        // 超时设置
        RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(param.getTimeout()).setConnectTimeout(param.getTimeout()).setConnectionRequestTimeout(param.getTimeout()).build();
        httpGet.setConfig(requestConfig);
        // head设置
        if (ObjUtils.isNotEmpty(param.getHeaderMap())) {
            for (Map.Entry<String, String> entry : param.getHeaderMap().entrySet()) {
                httpGet.setHeader(entry.getKey(), entry.getValue());
            }
        }
        // requestId
        String requestId = ObjUtils.ifEmpty(MDC.get(MDC_KEY_REQUESTID), MDC.get(MDC_KEY_REQUEST_ID));
        if (ObjUtils.isNotEmpty(requestId)) {
            httpGet.setHeader(MDC_KEY_REQUESTID, requestId);
        }
        httpclient = createHttpClient(param.getUrl());
        long start = System.currentTimeMillis();
        response = httpclient.execute(httpGet);
        long end = System.currentTimeMillis();
        int status = response.getStatusLine().getStatusCode();
        logger.info("请求url:{},结果状态:{},耗时:{}毫秒。", param.getUrl(), status, ((end - start)));
        HttpEntity entity = response.getEntity();
        return EntityUtils.toByteArray(entity);
    } catch (Exception e) {
        logger.error(e.getMessage(), e);
    } finally {
        org.apache.http.client.utils.HttpClientUtils.closeQuietly(response);
        org.apache.http.client.utils.HttpClientUtils.closeQuietly(httpclient);
    }
    return null;
}
Also used : CloseableHttpClient(org.apache.http.impl.client.CloseableHttpClient) RequestConfig(org.apache.http.client.config.RequestConfig) HttpEntity(org.apache.http.HttpEntity) HttpGet(org.apache.http.client.methods.HttpGet) CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse) LinkedHashMap(java.util.LinkedHashMap) Map(java.util.Map) CertificateException(java.security.cert.CertificateException)

Example 34 with RequestConfig

use of org.graylog.shaded.elasticsearch7.org.apache.http.client.config.RequestConfig in project pancm_project by xuwujing.

the class HttpClientUtil method get.

/**
 * 封装HTTP GET方法
 * 有参数的Get请求
 *
 * @param url 请求url     请求参数应该是  localhost:8080/test?name1=value1&name2=value2 的形式。
 * @return string
 * @throws Exception the exception
 */
public static String get(String url) throws Exception {
    CloseableHttpClient httpClient = null;
    HttpGet method = null;
    String body = null;
    try {
        httpClient = HttpClientBuilder.create().build();
        method = new HttpGet(url);
        // 增加http请求超时设置
        RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(10000).setConnectionRequestTimeout(30000).setSocketTimeout(60000).build();
        method.setConfig(requestConfig);
        if (method != null) {
            // 建立一个NameValuePair数组,用于存储欲传送的参数
            method.addHeader("Content-type", "application/json; charset=utf-8");
            method.setHeader("Accept", "application/json");
            HttpResponse response = httpClient.execute(method);
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode != HttpStatus.SC_OK) {
                logger.error("Method failed:" + response.getStatusLine());
                throw new Exception("statusCode:" + statusCode);
            }
            body = EntityUtils.toString(response.getEntity());
        }
    } catch (IOException e) {
        // 网络错误
        throw e;
    } finally {
        if (httpClient != null) {
            httpClient.close();
            httpClient = null;
            method = null;
        }
    }
    return body;
}
Also used : CloseableHttpClient(org.apache.http.impl.client.CloseableHttpClient) RequestConfig(org.apache.http.client.config.RequestConfig) HttpGet(org.apache.http.client.methods.HttpGet) HttpResponse(org.apache.http.HttpResponse) IOException(java.io.IOException) IOException(java.io.IOException)

Example 35 with RequestConfig

use of org.graylog.shaded.elasticsearch7.org.apache.http.client.config.RequestConfig in project pancm_project by xuwujing.

the class HttpClientUtil method httpsPost.

/**
 * post 请求
 *
 * @param postUrl    the post url
 * @param parameters the parameters
 * @return string
 * @throws Exception the exception
 */
public static String httpsPost(String postUrl, String parameters) throws Exception {
    CloseableHttpClient httpClient = null;
    HttpPost method = null;
    String body = null;
    try {
        // httpClient = HttpClientBuilder.create().build();
        httpClient = new SSLClient();
        method = new HttpPost(postUrl);
        // 增加http请求超时设置
        RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(60000).setConnectionRequestTimeout(60000).setSocketTimeout(60000).build();
        method.setConfig(requestConfig);
        if (method != null && parameters != null) {
            logger.info("请求接口的url地址:{},请求参数:{}", postUrl, JSONObject.toJSONString(parameters));
            // 建立一个NameValuePair数组,用于存储欲传送的参数
            method.addHeader("Content-type", "application/json; charset=utf-8");
            method.setHeader("Accept", "application/json");
            method.setEntity(new StringEntity(parameters, Charset.forName("UTF-8")));
            HttpResponse response = httpClient.execute(method);
            int statusCode = response.getStatusLine().getStatusCode();
            // logger.debug("statusCode:" + statusCode);
            if (statusCode != HttpStatus.SC_OK) {
                logger.error("Method failed:" + response.getStatusLine());
                logger.error("Request:" + parameters);
                throw new Exception("statusCode:" + statusCode);
            }
            // Read the response body
            body = EntityUtils.toString(response.getEntity());
        }
    } catch (IOException e) {
        // 网络错误
        throw e;
    } finally {
        if (httpClient != null) {
            httpClient.close();
            httpClient = null;
            method = null;
        }
    // logger.debug("调用接口状态:" + status);
    }
    logger.info("接口返回参数:{}!", body);
    return body;
}
Also used : CloseableHttpClient(org.apache.http.impl.client.CloseableHttpClient) HttpPost(org.apache.http.client.methods.HttpPost) RequestConfig(org.apache.http.client.config.RequestConfig) StringEntity(org.apache.http.entity.StringEntity) HttpResponse(org.apache.http.HttpResponse) IOException(java.io.IOException) IOException(java.io.IOException)

Aggregations

RequestConfig (org.apache.http.client.config.RequestConfig)344 CloseableHttpClient (org.apache.http.impl.client.CloseableHttpClient)146 CloseableHttpResponse (org.apache.http.client.methods.CloseableHttpResponse)97 HttpGet (org.apache.http.client.methods.HttpGet)94 IOException (java.io.IOException)78 HttpEntity (org.apache.http.HttpEntity)67 HttpPost (org.apache.http.client.methods.HttpPost)65 HttpResponse (org.apache.http.HttpResponse)60 HttpClientBuilder (org.apache.http.impl.client.HttpClientBuilder)55 URI (java.net.URI)46 StringEntity (org.apache.http.entity.StringEntity)43 Map (java.util.Map)41 Test (org.junit.Test)41 BasicCookieStore (org.apache.http.impl.client.BasicCookieStore)33 HttpHost (org.apache.http.HttpHost)32 PoolingHttpClientConnectionManager (org.apache.http.impl.conn.PoolingHttpClientConnectionManager)32 HttpClient (org.apache.http.client.HttpClient)31 BasicCredentialsProvider (org.apache.http.impl.client.BasicCredentialsProvider)27 UsernamePasswordCredentials (org.apache.http.auth.UsernamePasswordCredentials)24 SSLConnectionSocketFactory (org.apache.http.conn.ssl.SSLConnectionSocketFactory)24