Commit 73715d80ac2a174b16d7298bd18267a3f71a21cc
1 parent
ceee5fa6
1.HttpClients支持https请求
Showing
1 changed file
with
16 additions
and
3 deletions
src/main/java/com/bsth/util/HttpClientUtils.java
| ... | ... | @@ -19,6 +19,8 @@ import java.io.IOException; |
| 19 | 19 | import java.io.InputStreamReader; |
| 20 | 20 | import java.security.cert.CertificateException; |
| 21 | 21 | import java.security.cert.X509Certificate; |
| 22 | +import java.util.HashMap; | |
| 23 | +import java.util.Map; | |
| 22 | 24 | |
| 23 | 25 | /** |
| 24 | 26 | * Created by panzhao on 2017/8/2. |
| ... | ... | @@ -76,7 +78,7 @@ public class HttpClientUtils { |
| 76 | 78 | CloseableHttpResponse response = null; |
| 77 | 79 | StringBuilder stringBuffer = null; |
| 78 | 80 | try { |
| 79 | - httpClient = HttpClients.createDefault(); | |
| 81 | + httpClient = defaultHttpClient(url); | |
| 80 | 82 | HttpGet get = new HttpGet(url); |
| 81 | 83 | //超时时间 |
| 82 | 84 | RequestConfig requestConfig = RequestConfig.custom() |
| ... | ... | @@ -104,21 +106,32 @@ public class HttpClientUtils { |
| 104 | 106 | * @return |
| 105 | 107 | */ |
| 106 | 108 | public static StringBuilder post(String url, String data) throws Exception { |
| 109 | + return post(url, data, new HashMap<>()); | |
| 110 | + } | |
| 111 | + | |
| 112 | + public static StringBuilder post(String url, String data, Map<String, Object> headers) throws Exception { | |
| 107 | 113 | CloseableHttpClient httpClient = null; |
| 108 | 114 | CloseableHttpResponse response = null; |
| 109 | 115 | StringBuilder stringBuffer = null; |
| 110 | 116 | try { |
| 111 | - httpClient = HttpClients.createDefault(); | |
| 117 | + httpClient = defaultHttpClient(url); | |
| 112 | 118 | HttpPost post = new HttpPost(url); |
| 113 | 119 | |
| 114 | 120 | post.setHeader("Accept", "application/json"); |
| 115 | 121 | post.setHeader("Content-Type", "application/json;charset=UTF-8"); |
| 122 | + if (headers.size() > 0) { | |
| 123 | + for (Map.Entry<String, Object> header : headers.entrySet()) { | |
| 124 | + post.setHeader(header.getKey(), String.valueOf(header.getValue())); | |
| 125 | + } | |
| 126 | + } | |
| 116 | 127 | //超时时间 |
| 117 | 128 | RequestConfig requestConfig = RequestConfig.custom() |
| 118 | 129 | .setConnectTimeout(2500).setConnectionRequestTimeout(2000) |
| 119 | 130 | .setSocketTimeout(3500).build(); |
| 120 | 131 | post.setConfig(requestConfig); |
| 121 | - post.setEntity((new StringEntity(data, "UTF-8"))); | |
| 132 | + if (data != null) { | |
| 133 | + post.setEntity((new StringEntity(data, "UTF-8"))); | |
| 134 | + } | |
| 122 | 135 | |
| 123 | 136 | response = httpClient.execute(post); |
| 124 | 137 | stringBuffer = getResult(response.getEntity()); | ... | ... |