1. public class HttpUtils {
    2. private static String CHARSET = "UTF-8";
    3. //请求超时时间
    4. public static int socketTimeout = 30000;
    5. //传输超时时间
    6. public static int connectTimeout = 30000;
    7. private static final String HTTP = "http";
    8. private static final String HTTPS = "https";
    9. private static SSLConnectionSocketFactory sslsf = null;
    10. private static PoolingHttpClientConnectionManager cm = null;
    11. private static SSLContextBuilder builder = null;
    12. static {
    13. try {
    14. builder = new SSLContextBuilder();
    15. // 全部信任 不做身份鉴定
    16. builder.loadTrustMaterial(null, new TrustStrategy() {
    17. @Override
    18. public boolean isTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
    19. return true;
    20. }
    21. });
    22. sslsf = new SSLConnectionSocketFactory(builder.build(), new String[]{"SSLv2Hello", "SSLv3", "TLSv1", "TLSv1.2"}, null, NoopHostnameVerifier.INSTANCE);
    23. Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
    24. .register(HTTP, new PlainConnectionSocketFactory())
    25. .register(HTTPS, sslsf)
    26. .build();
    27. cm = new PoolingHttpClientConnectionManager(registry);
    28. cm.setMaxTotal(200);
    29. } catch (Exception e) {
    30. e.printStackTrace();
    31. }
    32. }
    33. public static CloseableHttpClient getHttpClient() {
    34. CloseableHttpClient httpClient = HttpClients.custom()
    35. .setSSLSocketFactory(sslsf)
    36. .setConnectionManager(cm)
    37. .setConnectionManagerShared(true)
    38. .build();
    39. return httpClient;
    40. }
    41. public static RequestConfig getConfig(){
    42. return RequestConfig.custom().setSocketTimeout(socketTimeout)
    43. .setConnectTimeout(connectTimeout).build();
    44. }
    45. public static <T>T sendGet(String url, Map<String,String> params, Map<String,String> headerMap, Class<T> javaType) {
    46. String apiUrl = url;
    47. StringBuffer param =new StringBuffer();
    48. int i =0;
    49. for (String key : params.keySet()) {
    50. if (i ==0){
    51. param.append("?");
    52. }else{
    53. param.append("&");
    54. }
    55. param.append(key).append("=").append(params.get(key));
    56. i++;
    57. }
    58. apiUrl += param;
    59. CloseableHttpClient httpclient = getHttpClient();;
    60. CloseableHttpResponse response =null;
    61. try {
    62. HttpGet httpGet =new HttpGet(apiUrl);
    63. httpGet.setConfig(getConfig());
    64. httpGet.setHeader("Content-Type", "application/json");
    65. if (httpGet != null && headerMap.size() != 0) {
    66. for (Map.Entry<String, String> entry : headerMap.entrySet()) {
    67. httpGet.addHeader(entry.getKey(), entry.getValue());
    68. }
    69. }
    70. //执行get请求
    71. response = httpclient.execute(httpGet);
    72. //返回结果
    73. int statusCode = response.getStatusLine().getStatusCode();
    74. if (statusCode == HttpStatus.SC_OK) {
    75. return httpOk(response,javaType);
    76. } else {
    77. return readHttpResponse(response,javaType);
    78. }
    79. }catch (IOException e) {
    80. e.printStackTrace();
    81. }finally {
    82. if (response !=null) {
    83. try {
    84. response.close();
    85. EntityUtils.consume(response.getEntity());
    86. }catch (IOException e) {
    87. e.printStackTrace();
    88. }
    89. }
    90. }
    91. return null;
    92. }
    93. /**
    94. * httpClient post请求
    95. * @param reqJson json数据
    96. * @return 可能为空 需要处理
    97. * @throws Exception
    98. */
    99. public static <T> T sendPost(String url, String reqJson, Map<String, String> headerMap, Class<T> javaType) {
    100. CloseableHttpClient httpClient = null;
    101. HttpResponse httpResponse=null;
    102. try {
    103. httpClient = getHttpClient();
    104. HttpPost httpPost = new HttpPost(url);
    105. httpPost.setConfig(getConfig());
    106. httpPost.setHeader("Content-Type", "application/json");
    107. if (headerMap != null && headerMap.size() != 0) {
    108. for (Map.Entry<String, String> entry : headerMap.entrySet()) {
    109. httpPost.addHeader(entry.getKey(), entry.getValue());
    110. }
    111. }
    112. StringEntity entity = new StringEntity(reqJson, CHARSET);
    113. entity.setContentEncoding(CHARSET);
    114. httpPost.setEntity(entity);
    115. //执行请求
    116. httpResponse = httpClient.execute(httpPost);
    117. //返回结果解析
    118. int statusCode = httpResponse.getStatusLine().getStatusCode();
    119. if (statusCode == HttpStatus.SC_OK) {
    120. return httpOk(httpResponse,javaType);
    121. } else {
    122. return readHttpResponse(httpResponse,javaType);
    123. }
    124. } catch (Exception e) {
    125. e.printStackTrace();
    126. } finally {
    127. if (httpClient != null) {
    128. try {
    129. httpClient.close();
    130. EntityUtils.consume(httpResponse.getEntity());
    131. }catch (IOException e) {
    132. e.printStackTrace();
    133. }
    134. }
    135. }
    136. return null;
    137. }
    138. /**
    139. * 发送 SSL POST 请求(HTTPS),K-V形式
    140. * @param
    141. */
    142. public static String doPostSSL(String url, Map<String,String> params) {
    143. CloseableHttpClient httpClient = getHttpClient();
    144. HttpPost httpPost =new HttpPost(url);
    145. CloseableHttpResponse response =null;
    146. String result =null;
    147. try {
    148. httpPost.setConfig(getConfig());
    149. List pairList =new ArrayList(params.size());
    150. for (Map.Entry entry : params.entrySet()) {
    151. NameValuePair pair =new BasicNameValuePair(entry.getKey().toString(), entry.getValue().toString());
    152. pairList.add(pair);
    153. }
    154. httpPost.setEntity(new UrlEncodedFormEntity(pairList, Charset.forName(CHARSET)));
    155. response = httpClient.execute(httpPost);
    156. int statusCode = response.getStatusLine().getStatusCode();
    157. if (statusCode != HttpStatus.SC_OK) {
    158. return null;
    159. }
    160. HttpEntity entity = response.getEntity();
    161. if (entity !=null) {
    162. result = EntityUtils.toString(entity,CHARSET);
    163. }
    164. }catch (Exception e) {
    165. e.printStackTrace();
    166. }finally {
    167. if (response !=null) {
    168. try {
    169. EntityUtils.consume(response.getEntity());
    170. }catch (IOException e) {
    171. e.printStackTrace();
    172. }
    173. }
    174. }
    175. return result;
    176. }
    177. /**
    178. * 发送 SSL POST 请求(HTTPS),JSON形式
    179. * @param
    180. */
    181. public static String doPostSSL(String url, Object json) {
    182. CloseableHttpClient httpClient =getHttpClient();
    183. HttpPost httpPost =new HttpPost(url);
    184. CloseableHttpResponse response =null;
    185. String result =null;
    186. try {
    187. httpPost.setConfig(getConfig());
    188. StringEntity stringEntity =new StringEntity(json.toString(),CHARSET);// 解决中文乱码问题
    189. stringEntity.setContentEncoding(CHARSET);
    190. stringEntity.setContentType("application/json");
    191. httpPost.setEntity(stringEntity);
    192. response = httpClient.execute(httpPost);
    193. int statusCode = response.getStatusLine().getStatusCode();
    194. if (statusCode != HttpStatus.SC_OK) {
    195. return null;
    196. }
    197. HttpEntity entity = response.getEntity();
    198. if (entity !=null) {
    199. result = EntityUtils.toString(entity,CHARSET);
    200. }
    201. }catch (Exception e) {
    202. e.printStackTrace();
    203. }finally {
    204. if (response !=null) {
    205. try {
    206. EntityUtils.consume(response.getEntity());
    207. }catch (IOException e) {
    208. e.printStackTrace();
    209. }
    210. }
    211. }
    212. return result;
    213. }
    214. /**
    215. * 原生字符串发送put请求
    216. * @param url
    217. * @param token
    218. * @param jsonStr
    219. * @return
    220. * @date 2019/6/17 17:46
    221. **/
    222. public static String doPut(String url, String token, String jsonStr) {
    223. CloseableHttpClient httpClient = HttpClients.createDefault();
    224. HttpPut httpPut =new HttpPut(url);
    225. httpPut.setConfig(getConfig());
    226. httpPut.setHeader("Content-type","application/json");
    227. httpPut.setHeader("DataEncoding",CHARSET);
    228. httpPut.setHeader("access-token", token);
    229. CloseableHttpResponse httpResponse =null;
    230. try {
    231. httpPut.setEntity(new StringEntity(jsonStr));
    232. httpResponse = httpClient.execute(httpPut);
    233. HttpEntity entity = httpResponse.getEntity();
    234. String result = EntityUtils.toString(entity);
    235. return result;
    236. }catch (ClientProtocolException e) {
    237. e.printStackTrace();
    238. }catch (IOException e) {
    239. e.printStackTrace();
    240. }finally {
    241. if (httpResponse !=null) {
    242. try {
    243. httpResponse.close();
    244. }catch (IOException e) {
    245. e.printStackTrace();
    246. }
    247. }
    248. if (null != httpClient) {
    249. try {
    250. httpClient.close();
    251. }catch (IOException e) {
    252. e.printStackTrace();
    253. }
    254. }
    255. }
    256. return null;
    257. }
    258. /**
    259. * 发送delete请求
    260. * @param url
    261. * @param token
    262. * @param jsonStr
    263. * @return
    264. * @date 2019/6/17 17:47
    265. **/
    266. public static String doDelete(String url, String token, String jsonStr) {
    267. CloseableHttpClient httpClient = HttpClients.createDefault();
    268. HttpDelete httpDelete =new HttpDelete(url);
    269. httpDelete.setConfig(getConfig());
    270. httpDelete.setHeader("Content-type","application/json");
    271. httpDelete.setHeader("DataEncoding",CHARSET);
    272. httpDelete.setHeader("access-token", token);
    273. CloseableHttpResponse httpResponse =null;
    274. try {
    275. httpResponse = httpClient.execute(httpDelete);
    276. HttpEntity entity = httpResponse.getEntity();
    277. String result = EntityUtils.toString(entity);
    278. return result;
    279. }catch (ClientProtocolException e) {
    280. e.printStackTrace();
    281. }catch (IOException e) {
    282. e.printStackTrace();
    283. }finally {
    284. if (httpResponse !=null) {
    285. try {
    286. httpResponse.close();
    287. }catch (IOException e) {
    288. e.printStackTrace();
    289. }
    290. }
    291. if (null != httpClient) {
    292. try {
    293. httpClient.close();
    294. }catch (IOException e) {
    295. e.printStackTrace();
    296. }
    297. }
    298. }
    299. return null;
    300. }
    301. private static <T>T httpOk(HttpResponse httpResponse,Class<T> javaType){
    302. HttpEntity resEntity = httpResponse.getEntity();
    303. String result = null;
    304. try {
    305. result = EntityUtils.toString(resEntity);
    306. ObjectMapper mapper=new ObjectMapper();
    307. T t = mapper.readValue(result, javaType);
    308. return t;
    309. } catch (IOException e) {
    310. e.printStackTrace();
    311. }
    312. return null;
    313. }
    314. public static <T>T readHttpResponse(HttpResponse httpResponse, Class<T> javaType)
    315. throws ParseException, IOException {
    316. StringBuilder builder = new StringBuilder();
    317. Map<String,String> resultMap= Maps.newHashMap();
    318. // 获取响应消息实体
    319. HttpEntity entity = httpResponse.getEntity();
    320. // 响应状态
    321. resultMap.put("code",httpResponse.getStatusLine().toString());
    322. HeaderIterator iterator = httpResponse.headerIterator();
    323. while (iterator.hasNext()) {
    324. builder.append("\t" + iterator.next());
    325. }
    326. resultMap.put("message",builder.toString());
    327. builder.delete(0,builder.length());
    328. // 判断响应实体是否为空
    329. if (entity != null) {
    330. String responseString = EntityUtils.toString(entity);
    331. builder.append(responseString.replace("\r\n", ""));
    332. }
    333. resultMap.put("errorData",builder.toString());
    334. //转成实体类
    335. String toJSON = JSONObject.toJSON(resultMap).toString();
    336. ObjectMapper mapper=new ObjectMapper();
    337. return mapper.readValue(toJSON, javaType);
    338. }
    339. }
    1. <dependency>
    2. <groupId>org.apache.httpcomponents</groupId>
    3. <artifactId>httpclient</artifactId>
    4. <version>4.5.13</version>
    5. </dependency>

    调用:

    1. HttpUtils.sendPost(healthRequest.getStudentReportList(pageNum,pageSize),json,
    2. healthRequest.getHeader(), RESTfulResultVO.class);
    3. HttpUtils.sendGet(healthRequest.getStudentReportInfo(reportId), Maps.newHashMap(),
    4. healthRequest.getHeader(),RESTfulResultVO.class);