HttpClient简单的实例:

实例:

  

  1 public class HttpClientUtils {
  2 
  3     public static final int connTimeout = 10000;
  4     public static final int readTimeout = 10000;
  5     public static final String charset = "UTF-8";
  6     private static HttpClient client = null;
  7 
  8     static {
  9         PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
 10         cm.setMaxTotal(128);
 11         cm.setDefaultMaxPerRoute(128);
 12         client = HttpClients.custom().setConnectionManager(cm).build();
 13     }
 14      //参数为map:示例:postParameters("http://www.baidu.com/login",map)
 15     public static String postParameters(String url, Map<String, Object> params) throws ConnectTimeoutException, SocketTimeoutException, Exception {
 16         return postMap(url, params, connTimeout, readTimeout);
 17     }
 18     //参数为json数据,
 19     public static String postParameters(String url, String params) throws IOException {
 20         return postJson(url, params);
 21     }
 22 
 23 
 24     /**
 25      * httpClient传递json
 26      *
 27      * @param url
 28      * @param body
 29      * @return
 30      * @throws IOException
 31      */
 32     public static String postJson(String url, String body) throws IOException {
 33         CloseableHttpClient httpClient = HttpClients.createDefault();
 34         HttpPost httpPost = new HttpPost(url);
 35         httpPost.addHeader("Content-Type", "application/json");
 36         httpPost.setEntity(new StringEntity(body));
 37 
 38         CloseableHttpResponse response = httpClient.execute(httpPost);
 39         HttpEntity entity = response.getEntity();
 40         String responseContent = EntityUtils.toString(entity, "UTF-8");
 41         response.close();
 42         httpClient.close();
 43         return responseContent;
 44     }
 45 
 46     /**
 47      * 传递map
 48      *
 49      * @param url
 50      * @param params
 51      * @param connTimeout
 52      * @param readTimeout
 53      * @return
 54      * @throws ConnectTimeoutException
 55      * @throws SocketTimeoutException
 56      * @throws Exception
 57      */
 58     public static String postMap(String url, Map<String, Object> params, Integer connTimeout, Integer readTimeout)
 59             throws ConnectTimeoutException, SocketTimeoutException, Exception {
 60 
 61         HttpClient client = null;
 62         HttpPost post = new HttpPost(url);
 63         try {
 64             if (params != null && !params.isEmpty()) {
 65                 List<NameValuePair> formParams = new ArrayList<NameValuePair>();
 66                 Set<Map.Entry<String, Object>> entrySet = params.entrySet();
 67                 for (Map.Entry<String, Object> entry : entrySet) {
 68                     formParams.add(new BasicNameValuePair(entry.getKey(), entry.getValue().toString()));
 69                 }
 70                 UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formParams, Consts.UTF_8);
 71                 post.setEntity(entity);
 72             }
 73 
 74             // 设置参数
 75             RequestConfig.Builder customReqConf = RequestConfig.custom();
 76             if (connTimeout != null) {
 77                 customReqConf.setConnectTimeout(connTimeout);
 78             }
 79             if (readTimeout != null) {
 80                 customReqConf.setSocketTimeout(readTimeout);
 81             }
 82             post.setConfig(customReqConf.build());
 83             HttpResponse res = null;
 84             if (url.startsWith("https")) {
 85                 // 执行 Https 请求.
 86                 client = createSSLInsecureClient();
 87                 res = client.execute(post);
 88             } else {
 89                 // 执行 Http 请求.
 90                 client = HttpClientUtils.client;
 91                 res = client.execute(post);
 92             }
 93             return IOUtils.toString(res.getEntity().getContent(), "UTF-8");
 94         } finally {
 95             post.releaseConnection();
 96             if (url.startsWith("https") && client != null && client instanceof CloseableHttpClient) {
 97                 ((CloseableHttpClient) client).close();
 98             }
 99         }
100     }
101 
102 
103     /**
104      * 创建 SSL连接
105      *
106      * @return
107      * @throws GeneralSecurityException
108      */
109     private static CloseableHttpClient createSSLInsecureClient() throws GeneralSecurityException {
110         try {
111             SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
112                 public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
113                     return true;
114                 }
115             }).build();
116             SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, new X509HostnameVerifier() {
117                 @Override
118                 public boolean verify(String arg0, SSLSession arg1) {
119                     return true;
120                 }
121 
122                 @Override
123                 public void verify(String host, SSLSocket ssl) throws IOException {
124                 }
125 
126                 @Override
127                 public void verify(String host, X509Certificate cert) throws SSLException {
128                 }
129 
130                 @Override
131                 public void verify(String host, String[] cns, String[] subjectAlts) throws SSLException {
132                 }
133             });
134             return HttpClients.custom().setSSLSocketFactory(sslsf).build();
135         } catch (GeneralSecurityException e) {
136             throw e;
137         }
138     }
139 
140 
141 }

 

转载于:https://www.cnblogs.com/wangyaobk/articles/7885104.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值