由于原本工具类中只有get和post请求方法,而工作中又需要用到put和delete请求来修改和删除数据,于是在get和post方法的基础上添加了put和delete请求方法。
其中put请求方法类似于post;delete方法类似于get。
1 /** 2 * 3 * 发送/获取HTTP请求的工具类 4 * 符合restAPI风格,分别有POST, DELETE, PUT, GET四种方法 5 * 分别对应增、删、改、查操作 6 * 7 */ 8 @Slf4j 9 public class HttpClientUtils { 10 private static final CloseableHttpClient httpClient; 11 public static final String CHARSET = "UTF-8"; 12 private final Logger logger = LoggerFactory.getLogger(getClass()); 13 static { 14 RequestConfig config = RequestConfig.custom() 15 .setConnectTimeout(8 * 1000) 16 .setSocketTimeout(8 * 1000) 17 .setConnectionRequestTimeout(8 * 1000) 18 .build(); 19 20 PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(); 21 cm.setMaxTotal(200); // 将最大连接数增加到200 22 cm.setDefaultMaxPerRoute(20); // 将每个路由基础的连接增加到20 23 24 //请求重试处理 25 HttpRequestRetryHandler httpRequestRetryHandler = new HttpRequestRetryHandler() { 26 public boolean retryRequest(IOException exception, int executionCount, HttpContext context) { 27 if (executionCount >= 5) {// 如果已经重试了5次,就放弃 28 return false; 29 } 30 if (exception instanceof NoHttpResponseException) {// 如果服务器丢掉了连接,那么就重试 31 return true; 32 } 33 if (exception instanceof SSLHandshakeException) {// 不要重试SSL握手异常 34 return false; 35 } 36 if (exception instanceof InterruptedIOException) {// 超时 37 return false; 38 } 39 if (exception instanceof UnknownHostException) {// 目标服务器不可达 40 return false; 41 } 42 if (exception instanceof ConnectTimeoutException) {// 连接被拒绝 43 return false; 44 } 45 if (exception instanceof SSLException) {// ssl握手异常 46 return false; 47 } 48 49 HttpClientContext clientContext = HttpClientContext.adapt(context); 50 HttpRequest request = clientContext.getRequest(); 51 // 如果请求是幂等的,就再次尝试 52 if (!(request instanceof HttpEntityEnclosingRequest)) { 53 return true; 54 } 55 return false; 56 } 57 }; 58 59 httpClient = HttpClientBuilder.create().setDefaultRequestConfig(config) 60 .setConnectionManager(cm) 61 .setRetryHandler(httpRequestRetryHandler) 62 .build(); 63 } 64 65 public static <T extends Object> String doGet(String url, Map<String, T> params) { 66 return doGet(url, params, null); 67 } 68 69 public static <T extends Object> String doGet(String url, Map<String, T> params, Map<String, String> headers) { 70 return doGet(url, params, CHARSET, headers); 71 } 72 73 public static <T extends Object> String doPost(String url, Map<String, T> params) { 74 return doPost(url, params, CHARSET); 75 } 76 77 /** 78 * HTTP Get 获取内容 79 * 80 * @param url 请求的url地址 ?之前的地址 81 * @param params 请求的参数 82 * @param charset 编码格式 83 * @return 页面内容 84 */ 85 public static <T extends Object> String doGet(String url, Map<String, T> params, String charset, 86 Map<String, String> headers) { 87 if (StringUtils.isBlank(url)) { 88 return null; 89 } 90 91 System.out.println("http:get:request:url: {"+url+"}, params:{"+params+"}"); 92 CloseableHttpResponse response = null; 93 String result = null; 94 95 HttpGet httpGet = null; 96 try { 97 if (params != null && !params.isEmpty()) { 98 List<NameValuePair> pairs = new ArrayList<>(params.size()); 99 for (Map.Entry<String, T> entry : params.entrySet()) { 100 Object value = entry.getValue(); 101 if (value != null) { 102 pairs.add(new BasicNameValuePair(entry.getKey(), value.toString())); 103 } 104 } 105 url += "?" + EntityUtils.toString(new UrlEncodedFormEntity(pairs, charset)); 106 } 107 System.out.println("url: {"+url+"}"); 108 httpGet = new HttpGet(url); 109 // header 110 if (headers != null && !headers.isEmpty()) { 111 for (String key : headers.keySet()) { 112 httpGet.setHeader(key, headers.get(key)); 113 } 114 } 115 116 response = httpClient.execute(httpGet); 117 118 int statusCode = response.getStatusLine().getStatusCode(); 119 if (statusCode != 200) { 120 httpGet.abort(); 121 throw new RuntimeException("HttpClient,error status code :" + statusCode); 122 } 123 124 } catch (Exception e) { 125 if (httpGet != null) { 126 httpGet.abort(); 127 } 128 System.out.println("<<<< exception: {"+e.getMessage()+"}" ); 129 e.printStackTrace(); 130 } finally { 131 if (response != null) { 132 HttpEntity entity = response.getEntity(); 133 134 if (entity != null) { 135 try { 136 result = EntityUtils.toString(entity, "utf-8"); 137 EntityUtils.consume(entity); 138 } catch (IOException e) { 139 e.printStackTrace(); 140 } 141 } 142 143 try { 144 response.close(); 145 } catch (IOException e) { 146 e.printStackTrace(); 147 } 148 } else { 149 System.out.println("<<<< response == null"); 150 } 151 } 152 System.out.println("http:get:result: {"+result+"}"); 153 return result; 154 } 155 156 /** 157 * HTTP Post 获取内容 158 * 159 * @param url 请求的url地址 ?之前的地址 160 * @param params 请求的参数 161 * @param charset 编码格式 162 * @return 页面内容 163 */ 164 public static <T extends Object> String doPost(String url, Map<String, T> params, String charset) { 165 if (StringUtils.isBlank(url)) { 166 return null; 167 } 168 System.out.println(" http:post:request:url: {"+url+"}, params:{"+params.toString()+"}" ); 169 CloseableHttpResponse response = null; 170 String result = null; 171 try { 172 List<NameValuePair> pairs = null; 173 if (params != null && !params.isEmpty()) { 174 pairs = new ArrayList<>(params.size()); 175 for (Map.Entry<String, T> entry : params.entrySet()) { 176 Object value = entry.getValue(); 177 if (value != null) { 178 pairs.add(new BasicNameValuePair(entry.getKey(), value.toString())); 179 } 180 } 181 } 182 HttpPost httpPost = new HttpPost(url); 183 if (pairs != null && pairs.size() > 0) { 184 httpPost.setEntity(new UrlEncodedFormEntity(pairs, CHARSET)); 185 } 186 response = httpClient.execute(httpPost); 187 int statusCode = response.getStatusLine().getStatusCode(); 188 if (statusCode != 200) { 189 httpPost.abort(); 190 throw new RuntimeException("HttpClient,error status code :" + statusCode); 191 } 192 HttpEntity entity = response.getEntity(); 193 if (entity != null) { 194 result = EntityUtils.toString(entity, "utf-8"); 195 } 196 EntityUtils.consume(entity); 197 } catch (Exception e) { 198 e.printStackTrace(); 199 } finally { 200 if (response != null) { 201 try { 202 response.close(); 203 } catch (IOException e) { 204 } 205 } 206 response = null; 207 } 208 System.out.println("http:post:result: {"+result+"}"); 209 return result; 210 } 211 212 213 214 /** 215 * 发送HTTP Delete请求 216 * 类似于GET 217 * @param url 请求的url地址 ?之前的地址 218 * @param params 请求的参数 219 * @return 页面内容 220 */ 221 public static <T extends Object> String doDelete(String url, Map<String, T> params, Map<String, String> headers) { 222 if (StringUtils.isBlank(url)) { 223 return null; 224 } 225 226 System.out.println("http:delete:request:url: {"+url+"}, params:{"+params+"}"); 227 CloseableHttpResponse response = null; 228 String result = null; 229 230 HttpDelete httpDelete = null; 231 try { 232 if (params != null && !params.isEmpty()) { 233 List<NameValuePair> pairs = new ArrayList<>(params.size()); 234 for (Map.Entry<String, T> entry : params.entrySet()) { 235 Object value = entry.getValue(); 236 if (value != null) { 237 pairs.add(new BasicNameValuePair(entry.getKey(), value.toString())); 238 } 239 } 240 url += "?" + EntityUtils.toString(new UrlEncodedFormEntity(pairs, CHARSET)); 241 } 242 System.out.println("url: {"+url+"}"); 243 httpDelete = new HttpDelete(url); 244 // header 245 if (headers != null && !headers.isEmpty()) { 246 for (String key : headers.keySet()) { 247 httpDelete.setHeader(key, headers.get(key)); 248 } 249 } 250 251 response = httpClient.execute(httpDelete); 252 253 int statusCode = response.getStatusLine().getStatusCode(); 254 if (statusCode != 200) { 255 httpDelete.abort(); 256 throw new RuntimeException("HttpClient,error status code :" + statusCode); 257 } 258 259 } catch (Exception e) { 260 if (httpDelete != null) { 261 httpDelete.abort(); 262 } 263 System.out.println("<<<< exception: {"+e.getMessage()+"}" ); 264 e.printStackTrace(); 265 } finally { 266 if (response != null) { 267 HttpEntity entity = response.getEntity(); 268 269 if (entity != null) { 270 try { 271 result = EntityUtils.toString(entity, "utf-8"); 272 EntityUtils.consume(entity); 273 } catch (IOException e) { 274 e.printStackTrace(); 275 } 276 } 277 278 try { 279 response.close(); 280 } catch (IOException e) { 281 e.printStackTrace(); 282 } 283 } else { 284 System.out.println("<<<< response == null"); 285 } 286 } 287 System.out.println("http:delete:result: {"+result+"}"); 288 return result; 289 } 290 291 292 /** 293 * HTTP Put 获取内容 294 * 类似于POST 295 * @param url 请求的url地址 ?之前的地址 296 * @param params 请求的参数 297 * @return 页面内容 298 */ 299 public static <T extends Object> String doPut(String url, Map<String, T> params) { 300 if (StringUtils.isBlank(url)) { 301 return null; 302 } 303 System.out.println(" http:post:request:url: {"+url+"}, params:{"+params.toString()+"}" ); 304 CloseableHttpResponse response = null; 305 String result = null; 306 try { 307 List<NameValuePair> pairs = null; 308 if (params != null && !params.isEmpty()) { 309 pairs = new ArrayList<>(params.size()); 310 for (Map.Entry<String, T> entry : params.entrySet()) { 311 Object value = entry.getValue(); 312 if (value != null) { 313 pairs.add(new BasicNameValuePair(entry.getKey(), value.toString())); 314 } 315 } 316 } 317 HttpPut httpPut = new HttpPut(url); 318 if (pairs != null && pairs.size() > 0) { 319 httpPut.setEntity(new UrlEncodedFormEntity(pairs, CHARSET)); 320 } 321 response = httpClient.execute(httpPut); 322 int statusCode = response.getStatusLine().getStatusCode(); 323 if (statusCode != 200) { 324 httpPut.abort(); 325 throw new RuntimeException("HttpClient,error status code :" + statusCode); 326 } 327 HttpEntity entity = response.getEntity(); 328 if (entity != null) { 329 result = EntityUtils.toString(entity, CHARSET); 330 } 331 EntityUtils.consume(entity); 332 } catch (Exception e) { 333 e.printStackTrace(); 334 } finally { 335 if (response != null) { 336 try { 337 response.close(); 338 } catch (IOException e) { 339 } 340 } 341 response = null; 342 } 343 System.out.println("http:post:result: {"+result+"}"); 344 return result; 345 } 346 347 }