httpClient4.5创建连接池进行post请求

测试demo导入的jar:
1.httpclient-4.5.jar
2.httpcore-4.4.1.jar
3.httpmime-4.0.1.jar
4.commons-logging-1.1.1.jar

/**
* httpClient连接池创建
*
* 1. [假设Java和Apache的HttpClient的] 使用ThreadSafeClientConnManager。通过一个单一的全局实例,
* 每一个HttpClient的实例的构造函数。我不认为有一个在凝聚HttpClients自己的任何一点。
*
* 2. 对于HttpClient的4倍: ThreadSafeClientConnManager …管理客户端端池 连接,并能够服务来自多个执行线程的连接请求。
* 连接池在每个路线的基础。针对该路由请求的管理已经 已在池中可用的持久连接将由租赁的连接提供服务 池而不是创建一个全新的连接。
*
* 3. 现在ThreadSafeClientConnManager已过时,使用PoolingClientConnectionManager代替。
*
* 4. 现在PoolingClientConnectionManager被弃用。从(4.3版本)使用PoolingHttpClientConnectionManager
* @author 先森怪兽赵丶
*
*/

public class HttpClient4Test {

private PoolingHttpClientConnectionManager poolConnManager;
private final int maxTotalPool = 200;
private final int maxConPerRoute = 20;
private final int socketTimeout = 2000;
private final int connectionRequestTimeout = 3000;
private final int connectTimeout = 1000;

public void init(){  
 try {  
    SSLContext sslcontext = SSLContexts.custom().loadTrustMaterial(null,  
                    new TrustSelfSignedStrategy())  
            .build();  
    HostnameVerifier hostnameVerifier = SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER;  
    SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(  
            sslcontext,hostnameVerifier);  
    Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()  
            .register("http", PlainConnectionSocketFactory.getSocketFactory())  
            .register("https", sslsf)  
            .build();  
    poolConnManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);  
    // Increase max total connection to 200  
    poolConnManager.setMaxTotal(maxTotalPool);  
    // Increase default max connection per route to 20  
    poolConnManager.setDefaultMaxPerRoute(maxConPerRoute);  
    SocketConfig socketConfig = SocketConfig.custom().setSoTimeout(socketTimeout).build();  
    poolConnManager.setDefaultSocketConfig(socketConfig);  
} catch (Exception e) {  

}  

}

public CloseableHttpClient getConnection(){  
    RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(connectionRequestTimeout)  
            .setConnectTimeout(connectTimeout).setSocketTimeout(socketTimeout).build();  
    CloseableHttpClient httpClient = HttpClients.custom()  
                .setConnectionManager(poolConnManager).setDefaultRequestConfig(requestConfig).build();  
    if(poolConnManager!=null&&poolConnManager.getTotalStats()!=null){  

        System.out.println("now client pool "+poolConnManager.getTotalStats().toString());  
    }  
    return httpClient;  
} 


public String postMsg(String url, String jsonStr)  
{  
    String returnStr = null;  
    //参数检测  
    if(url==null||"".equals(url))  
    {  
        return returnStr;  
    }  
    HttpPost httpPost = new HttpPost(url);  
    try {  


        List <NameValuePair> nvps = new ArrayList <NameValuePair>();  
        nvps.add(new BasicNameValuePair("jsonstr", jsonStr));  
        httpPost.setEntity(new UrlEncodedFormEntity(nvps, "UTF-8"));  
        System.out.println(" 开始发送 请求:url"+url);  

        CloseableHttpClient client = this.getConnection();
        CloseableHttpResponse response = client.execute(httpPost);  
        int status = response.getStatusLine().getStatusCode();  
        if (status >= 200 && status < 300) {  
            HttpEntity entity = response.getEntity();  
            String resopnse="";  
            if(entity != null)  
            {  
                resopnse=EntityUtils.toString(entity,"utf-8");  
            }  
            System.out.println(" 接收响应:url"+url+" status="+status);  
            return entity != null ? resopnse : null;  
        } else {  
            HttpEntity entity = response.getEntity();  
            httpPost.abort();  
            System.out.println(" 接收响应:url"+url+" status="+status+" resopnse="+EntityUtils.toString(entity,"utf-8"));  
            throw new ClientProtocolException("Unexpected response status: " + status);  
        }  
    } catch (Exception e) {  
        httpPost.abort();  
        System.out.println(" Exception"+e.toString()+" url="+url+" jsonstr="+jsonStr);  
    }   
    return returnStr;  
}

public static void main(String[] args) {
    TestDemo02 demo02 = new TestDemo02();
    String url = "http://192.168.1.1/interface!sendMsg.action";
    String result = demo02.postMsg(url, "123");
    System.out.println(result);
}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
使用HttpClient发送HTTPS请求并配置连接池,可以按照以下步骤进行: 1. 创建SSLContext对象,用于HTTPS连接的安全认证。 ```java SSLContext sslContext = SSLContexts.createSystemDefault(); ``` 2. 创建ConnectionSocketFactory对象,用于连接池中的连接创建。 ```java SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(sslContext); ``` 3. 创建HttpClientConnectionManager对象,用于管理连接池中的连接。 ```java PoolingHttpClientConnectionManager poolingHttpClientConnectionManager = new PoolingHttpClientConnectionManager(Arrays.asList(sslConnectionSocketFactory)); poolingHttpClientConnectionManager.setMaxTotal(200);//设置最大连接数 poolingHttpClientConnectionManager.setDefaultMaxPerRoute(100);//设置每个路由最大连接数 ``` 4. 创建HttpClient对象,并设置连接池管理器。 ```java CloseableHttpClient httpClient = HttpClients.custom() .setConnectionManager(poolingHttpClientConnectionManager) .build(); ``` 5. 创建HttpPost对象,设置请求参数,并执行请求。 ```java HttpPost httpPost = new HttpPost("https://example.com/path"); httpPost.setEntity(new StringEntity("Hello, world!")); CloseableHttpResponse httpResponse = httpClient.execute(httpPost); ``` 完整的示例代码如下: ```java import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; import org.apache.http.ssl.SSLContexts; import org.apache.http.conn.ssl.SSLConnectionSocketFactory; import javax.net.ssl.SSLContext; import java.util.Arrays; import java.io.IOException; public class HttpClientExample { public static void main(String[] args) throws IOException { SSLContext sslContext = SSLContexts.createSystemDefault(); SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(sslContext); PoolingHttpClientConnectionManager poolingHttpClientConnectionManager = new PoolingHttpClientConnectionManager(Arrays.asList(sslConnectionSocketFactory)); poolingHttpClientConnectionManager.setMaxTotal(200); poolingHttpClientConnectionManager.setDefaultMaxPerRoute(100); CloseableHttpClient httpClient = HttpClients.custom() .setConnectionManager(poolingHttpClientConnectionManager) .build(); HttpPost httpPost = new HttpPost("https://example.com/path"); httpPost.setEntity(new StringEntity("Hello, world!")); CloseableHttpResponse httpResponse = httpClient.execute(httpPost); System.out.println(httpResponse.getStatusLine().getStatusCode()); httpResponse.close(); httpClient.close(); } } ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值