1.引入相关依赖
<dependency>
<groupId>org.apache.httpcomponents</groupId> <artifactId>httpmime</artifactId> <version>4.5.4</version> </dependency> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-lang3</artifactId> <version>3.6</version> </dependency> 2.http客户端参数类 import lombok.Getter; import lombok.Setter; import org.springframework.boot.context.properties.ConfigurationProperties; @ConfigurationProperties(prefix = "operation.httpclient") @Getter @Setter public class HttpClientProperties { private String maxTotal; private String maxPerRoute; private String timeOut; private String needretry; } 3.工具类 import org.apache.commons.lang3.StringUtils; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.client.config.RequestConfig; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.*; import org.apache.http.conn.ConnectTimeoutException; import org.apache.http.conn.HttpHostConnectException; import org.apache.http.entity.StringEntity; import org.apache.http.entity.mime.MultipartEntityBuilder; import org.apache.http.entity.mime.content.FileBody; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.DefaultHttpRequestRetryHandler; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; import org.apache.http.message.BasicNameValuePair; import org.apache.http.util.EntityUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; public class HttpTookit { private static Logger logger = LoggerFactory.getLogger(HttpTookit.class); private static final CloseableHttpClient httpClient; public static final String CHARSET = "UTF-8"; private static int timeout = 360000; private static boolean needRetry = false; private static HttpClientProperties properties = new HttpClientProperties(); public HttpTookit() { } public static boolean initParms() { return true; } public static String doGet(String url, Map<String, String> params) { return doGet(url, params, null, "UTF-8"); } public static String doPost(String url, Map<String, String> params) { return doPost(url, params, null, "UTF-8"); } public static String doDelete(String url, Map<String, String> params) { return doDelete(url, params, null, "UTF-8"); } public static String doPut(String url, Map<String, String> params) { return doPut(url, params, null, "UTF-8"); } public static String doGet(String url, Map<String, String> params, Map<String, String> headers) { return doGet(url, params, headers, "UTF-8"); } public static String doPost(String url, Map<String, String> params, Map<String, String> headers) { return doPost(url, params, headers, "UTF-8"); } public static String doDelete(String url, Map<String, String> params, Map<String, String> headers) { return doDelete(url, params, headers, "UTF-8"); } public static String doPostWithJson(String url, String json, Map<String, String> headers) { return doPostWithJson(url, json, headers, "UTF-8"); } public static String doPut(String url, Map<String, String> params, Map<String, String> headers) { return doPut(url, params, headers, "UTF-8"); } public static String doPostFile(String url, Map<String, String> params, Map<String, String> headers, String filepath) { return doPostFile(url, params, headers, filepath, "UTF-8"); } public static String doGet(String url, Map<String, String> params, Map<String, String> headers, String charset) { if (StringUtils.isBlank(url)) { return null; } else { try { Iterator i$; Entry entry; if (params != null && !params.isEmpty()) { List<NameValuePair> pairs = new ArrayList(params.size()); i$ = params.entrySet().iterator(); while (i$.hasNext()) { entry = (Entry) i$.next(); String value = (String) entry.getValue(); if (value != null) { pairs.add(new BasicNameValuePair((String) entry.getKey(), value)); } } url = url + "?" + EntityUtils.toString(new UrlEncodedFormEntity(pairs, charset)); } HttpGet httpGet = new HttpGet(url); if (headers != null && !headers.isEmpty()) { i$ = headers.entrySet().iterator(); while (i$.hasNext()) { entry = (Entry) i$.next(); httpGet.addHeader((String) entry.getKey(), (String) entry.getValue()); } } RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(timeout).setConnectTimeout(timeout).build(); httpGet.setConfig(requestConfig); entry = null; CloseableHttpResponse response; try { response = httpClient.execute(httpGet); } catch (HttpHostConnectException | ConnectTimeoutException var10) { logger.error("connect timeout, will reconnect", var10); response = httpClient.execute(httpGet); } int statusCode = response.getStatusLine().getStatusCode(); if (statusCode != 200) { httpGet.abort(); throw new RuntimeException("HttpClient,error status code :" + statusCode); } else { HttpEntity entity = response.getEntity(); String result = null; if (entity != null) { result = EntityUtils.toString(entity, "utf-8"); } EntityUtils.consume(entity); response.close(); httpGet.releaseConnection(); return result; } } catch (Exception var11) { logger.error("Exception e " + var11.getMessage(), var11); return null; } } } public static String doPost(String url, Map<String, String> params, Map<String, String> headers, String charset) { if (StringUtils.isBlank(url)) { return null; } else { try { List<NameValuePair> pairs = null; if (params != null && !params.isEmpty()) { pairs = new ArrayList(params.size()); Iterator i$ = params.entrySet().iterator(); while (i$.hasNext()) { Entry<String, String> entry = (Entry) i$.next(); String value = entry.getValue(); if (StringUtils.isNotBlank(value)) { pairs.add(new BasicNameValuePair(entry.getKey(), value)); } } } HttpPost httpPost = new HttpPost(url); if (pairs != null && pairs.size() > 0) { httpPost.setEntity(new UrlEncodedFormEntity(pairs, "UTF-8")); } if (headers != null && !headers.isEmpty()) { Iterator i$ = headers.entrySet().iterator(); while (i$.hasNext()) { Entry<String, String> entry = (Entry) i$.next(); httpPost.addHeader(entry.getKey(), entry.getValue()); } } RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(timeout).setConnectTimeout(timeout).build(); httpPost.setConfig(requestConfig); CloseableHttpResponse response = httpClient.execute(httpPost); int statusCode = response.getStatusLine().getStatusCode(); if (statusCode != 200) { httpPost.abort(); throw new RuntimeException("HttpClient,error status code :" + statusCode); } else { HttpEntity entity = response.getEntity(); String result = null; if (entity != null) { result = EntityUtils.toString(entity, "utf-8"); } EntityUtils.consume(entity); response.close(); httpPost.releaseConnection(); return result; } } catch (Exception var11) { logger.error("Exception e " + var11.getMessage(), var11); return null; } } } public static String doPostFile(String url, Map<String, String> params, Map<String, String> headers, String filepath, String charset) { if (StringUtils.isBlank(url)) { return null; } else { try { FileBody bin = new FileBody(new File(filepath)); MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.addPart("file", bin); HttpPost httpPost = new HttpPost(url); httpPost.setEntity(builder.build()); if (headers != null && !headers.isEmpty()) { Iterator i$ = headers.entrySet().iterator(); while (i$.hasNext()) { Entry<String, String> entry = (Entry) i$.next(); httpPost.addHeader(entry.getKey(), entry.getValue()); } } HttpResponse response = httpClient.execute(httpPost); int statusCode = response.getStatusLine().getStatusCode(); if (statusCode != 200) { httpPost.abort(); throw new RuntimeException("HttpClient,error status code :" + statusCode); } else { HttpEntity entity = response.getEntity(); String result = null; if (entity != null) { result = EntityUtils.toString(entity, "utf-8"); } EntityUtils.consume(entity); httpPost.releaseConnection(); return result; } } catch (Exception var12) { logger.error("Exception e " + var12.getMessage(), var12); return null; } } } public static String doPostWithJson(String url, String json, Map<String, String> headers, String charset) { if (StringUtils.isBlank(url)) { return null; } else { try { HttpPost httpPost = new HttpPost(url); if (headers != null && !headers.isEmpty()) { for (Object o : headers.entrySet()) { Entry<String, String> entry = (Entry) o; httpPost.addHeader(entry.getKey(), entry.getValue()); } } StringEntity s = new StringEntity(json, "UTF-8"); s.setContentEncoding("UTF-8"); s.setContentType("application/json"); httpPost.setEntity(s); RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(timeout).setConnectTimeout(timeout).build(); httpPost.setConfig(requestConfig); CloseableHttpResponse response = httpClient.execute(httpPost); int statusCode = response.getStatusLine().getStatusCode(); if (statusCode != 200) { httpPost.abort(); throw new RuntimeException("HttpClient,error status code :" + statusCode); } else { HttpEntity entity = response.getEntity(); String result = null; if (entity != null) { result = EntityUtils.toString(entity, "utf-8"); } EntityUtils.consume(entity); response.close(); httpPost.releaseConnection(); return result; } } catch (Exception var11) { logger.error("Exception e " + var11.getMessage(), var11); return null; } } } public static String doDelete(String url, Map<String, String> params, Map<String, String> headers, String charset) { if (StringUtils.isBlank(url)) { return null; } else { try { Iterator i$; Entry entry; if (params != null && !params.isEmpty()) { List<NameValuePair> pairs = new ArrayList(params.size()); i$ = params.entrySet().iterator(); while (i$.hasNext()) { entry = (Entry) i$.next(); String value = (String) entry.getValue(); if (value != null) { pairs.add(new BasicNameValuePair((String) entry.getKey(), value)); } } url = url + "?" + EntityUtils.toString(new UrlEncodedFormEntity(pairs, charset)); } HttpDelete httpDelete = new HttpDelete(url); if (headers != null && !headers.isEmpty()) { i$ = headers.entrySet().iterator(); while (i$.hasNext()) { entry = (Entry) i$.next(); httpDelete.addHeader((String) entry.getKey(), (String) entry.getValue()); } } RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(timeout).setConnectTimeout(timeout).build(); httpDelete.setConfig(requestConfig); CloseableHttpResponse response = httpClient.execute(httpDelete); int statusCode = response.getStatusLine().getStatusCode(); if (statusCode != 200) { httpDelete.abort(); throw new RuntimeException("HttpClient,error status code :" + statusCode); } else { HttpEntity entity = response.getEntity(); String result = null; if (entity != null) { result = EntityUtils.toString(entity, "utf-8"); } EntityUtils.consume(entity); response.close(); httpDelete.releaseConnection(); return result; } } catch (Exception var10) { logger.error("Exception e " + var10.getMessage(), var10); return null; } } } public static String doPut(String url, Map<String, String> params, Map<String, String> headers, String charset) { if (StringUtils.isBlank(url)) { return null; } else { try { List<NameValuePair> pairs = null; if (params != null && !params.isEmpty()) { pairs = new ArrayList(params.size()); Iterator i$ = params.entrySet().iterator(); while (i$.hasNext()) { Entry<String, String> entry = (Entry) i$.next(); String value = entry.getValue(); if (value != null) { pairs.add(new BasicNameValuePair(entry.getKey(), value)); } } } HttpPut httpPut = new HttpPut(url); if (pairs != null && pairs.size() > 0) { httpPut.setEntity(new UrlEncodedFormEntity(pairs, "UTF-8")); } if (headers != null && !headers.isEmpty()) { Iterator i$ = headers.entrySet().iterator(); while (i$.hasNext()) { Entry<String, String> entry = (Entry) i$.next(); httpPut.addHeader(entry.getKey(), entry.getValue()); } } CloseableHttpResponse response = httpClient.execute(httpPut); int statusCode = response.getStatusLine().getStatusCode(); if (statusCode != 200) { httpPut.abort(); throw new RuntimeException("HttpClient,error status code :" + statusCode); } else { HttpEntity entity = response.getEntity(); String result = null; if (entity != null) { result = EntityUtils.toString(entity, "utf-8"); } EntityUtils.consume(entity); response.close(); httpPut.releaseConnection(); return result; } } catch (Exception var10) { logger.error("Exception e " + var10.getMessage(), var10); return null; } } } public static void setProperties(HttpClientProperties properties) { HttpTookit.properties = properties; } static { String maxTotal = HttpTookit.properties.getMaxTotal(); String maxPerRoute = HttpTookit.properties.getMaxPerRoute(); if (maxTotal == null) { maxTotal = "100"; } if (maxPerRoute == null) { maxPerRoute = "100"; } String timeOut = HttpTookit.properties.getTimeOut(); if (timeOut != null) { try { timeout = Integer.valueOf(timeOut).intValue(); if (timeout > 500) { timeout = 500; } timeout *= 1000; } catch (Exception var8) { logger.error("Exception e " + var8.getMessage(), var8); } } RequestConfig config = RequestConfig.custom().setConnectTimeout(timeout).setSocketTimeout(timeout).build(); PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(); cm.setMaxTotal(Integer.valueOf(maxTotal).intValue()); cm.setDefaultMaxPerRoute(Integer.valueOf(maxPerRoute).intValue()); String retryStr = HttpTookit.properties.getNeedretry(); if (retryStr != null) { needRetry = Boolean.valueOf(retryStr).booleanValue(); } if (needRetry) { httpClient = HttpClientBuilder.create().setDefaultRequestConfig(config).setConnectionManager(cm).setRetryHandler(new DefaultHttpRequestRetryHandler(3, false)).build(); } else { httpClient = HttpClientBuilder.create().setDefaultRequestConfig(config).setConnectionManager(cm).build(); } } }
Java后台发送Http请求
猜你喜欢
转载自www.cnblogs.com/dychf/p/9665771.html
今日推荐
周排行