org.apache.httpcomponents:httpclient 工具类
程序员文章站
2022-05-14 23:37:59
...
基于httpclient 版本4.4.1
因为http连接需要三次握手,在需要频繁调用时浪费资源和时间
故采用连接池的方式连接
根据实际需要更改 连接池最大连接数、路由最大连接数
另一个需要注意的是
// 释放Socket流 response.close(); // 释放Connection // httpClient.close();
1 import org.apache.http.HttpEntity; 2 import org.apache.http.NameValuePair; 3 import org.apache.http.client.config.RequestConfig; 4 import org.apache.http.client.entity.UrlEncodedFormEntity; 5 import org.apache.http.client.methods.CloseableHttpResponse; 6 import org.apache.http.client.methods.HttpGet; 7 import org.apache.http.client.methods.HttpPost; 8 import org.apache.http.client.methods.HttpRequestBase; 9 import org.apache.http.client.utils.URIBuilder; 10 import org.apache.http.config.SocketConfig; 11 import org.apache.http.entity.StringEntity; 12 import org.apache.http.impl.client.CloseableHttpClient; 13 import org.apache.http.impl.client.HttpClients; 14 import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; 15 import org.apache.http.message.BasicNameValuePair; 16 import org.apache.http.util.EntityUtils; 17 18 import java.io.IOException; 19 import java.io.UnsupportedEncodingException; 20 import java.net.URISyntaxException; 21 import java.util.ArrayList; 22 import java.util.Map; 23 24 /** 25 * Created by lidada on 2017/6/9. 26 */ 27 public class HttpClientUtils { 28 private static PoolingHttpClientConnectionManager cm; 29 private static String EMPTY_STR = ""; 30 private static String CONTENT_TYPE_UTF_8 = "UTF-8"; 31 private static String CONTENT_TYPE_GBK = "GBK"; 32 private static String CONTENT_TYPE_JSON = "application/json"; 33 private static final int CONNECTION_TIMEOUT_MS = 60000; 34 private static final int SO_TIMEOUT_MS = 60000; 35 36 private static void init() { 37 if (cm == null) { 38 cm = new PoolingHttpClientConnectionManager(); 39 cm.setMaxTotal(50);// 整个连接池最大连接数 40 cm.setDefaultMaxPerRoute(5);// 每路由最大连接数,默认值是2 41 SocketConfig sc = SocketConfig.custom().setSoTimeout(SO_TIMEOUT_MS).build(); 42 cm.setDefaultSocketConfig(sc); 43 } 44 } 45 46 /** 47 * 通过连接池获取HttpClient 48 * 49 * @return 50 */ 51 private static CloseableHttpClient getHttpClient() { 52 init(); 53 return HttpClients.custom().setConnectionManager(cm).setConnectionManagerShared(true) .build(); 54 } 55 56 public static String httpGetRequest(String url) { 57 HttpGet httpGet = new HttpGet(url); 58 return getResult(httpGet); 59 } 60 61 public static String httpGetRequest(String url, Map<String, Object> params) throws URISyntaxException { 62 URIBuilder ub = new URIBuilder(); 63 ub.setPath(url); 64 65 ArrayList<NameValuePair> pairs = covertParams2NVPS(params); 66 ub.setParameters(pairs); 67 68 HttpGet httpGet = new HttpGet(ub.build()); 69 return getResult(httpGet); 70 } 71 72 public static String httpGetRequest(String url, Map<String, Object> headers, Map<String, Object> params) 73 throws URISyntaxException { 74 URIBuilder ub = new URIBuilder(); 75 ub.setPath(url); 76 77 ArrayList<NameValuePair> pairs = covertParams2NVPS(params); 78 ub.setParameters(pairs); 79 80 HttpGet httpGet = new HttpGet(ub.build()); 81 for (Map.Entry<String, Object> param : headers.entrySet()) { 82 httpGet.addHeader(param.getKey(), String.valueOf(param.getValue())); 83 } 84 return getResult(httpGet); 85 } 86 87 public static String httpPostRequest(String url) { 88 HttpPost httpPost = new HttpPost(url); 89 return getResult(httpPost); 90 } 91 92 public static String httpPostRequest(String url, Map<String, Object> params) throws UnsupportedEncodingException { 93 HttpPost httpPost = new HttpPost(url); 94 ArrayList<NameValuePair> pairs = covertParams2NVPS(params); 95 httpPost.setEntity(new UrlEncodedFormEntity(pairs, CONTENT_TYPE_UTF_8)); 96 return getResult(httpPost); 97 } 98 99 public static String httpPostRequest(String url, Map<String, Object> headers, Map<String, Object> params) 100 throws UnsupportedEncodingException { 101 HttpPost httpPost = new HttpPost(url); 102 103 for (Map.Entry<String, Object> param : headers.entrySet()) { 104 httpPost.addHeader(param.getKey(), String.valueOf(param.getValue())); 105 } 106 107 ArrayList<NameValuePair> pairs = covertParams2NVPS(params); 108 httpPost.setEntity(new UrlEncodedFormEntity(pairs, CONTENT_TYPE_UTF_8)); 109 110 return getResult(httpPost); 111 } 112 113 public static String httpPostJSON(String url, String json) throws UnsupportedEncodingException { 114 HttpPost httpPost = new HttpPost(url); 115 StringEntity s = new StringEntity(json); 116 s.setContentEncoding(CONTENT_TYPE_UTF_8); 117 s.setContentType(CONTENT_TYPE_JSON);// 发送json数据需要设置contentType 118 httpPost.setEntity(s); 119 return getResult(httpPost); 120 } 121 122 123 private static ArrayList<NameValuePair> covertParams2NVPS(Map<String, Object> params) { 124 ArrayList<NameValuePair> pairs = new ArrayList<>(); 125 for (Map.Entry<String, Object> param : params.entrySet()) { 126 pairs.add(new BasicNameValuePair(param.getKey(), String.valueOf(param.getValue()))); 127 } 128 129 return pairs; 130 } 131 132 /** 133 * 处理Http请求 134 * 135 * @param request 136 * @return 137 */ 138 private static String getResult(HttpRequestBase request) { 139 140 RequestConfig.Builder config = RequestConfig.copy(RequestConfig.DEFAULT); 141 config.setConnectionRequestTimeout(CONNECTION_TIMEOUT_MS); 142 config.setSocketTimeout(SO_TIMEOUT_MS); 143 144 request.setConfig(config.build()); 145 146 // CloseableHttpClient httpClient = HttpClients.createDefault(); 147 CloseableHttpClient httpClient = getHttpClient(); 148 CloseableHttpResponse response = null; 149 try { 150 response = httpClient.execute(request); 151 // response.getStatusLine().getStatusCode(); 152 HttpEntity entity = response.getEntity(); 153 if (entity != null) { 154 // long len = entity.getContentLength();// -1 表示长度未知 155 return EntityUtils.toString(entity); 156 } 157 } catch (IOException e) { 158 e.printStackTrace(); 159 } finally { 160 try { 161 // 释放Socket流 162 response.close(); 163 // 释放Connection 164 // httpClient.close(); 165 } catch (IOException e) { 166 e.printStackTrace(); 167 } 168 } 169 170 return EMPTY_STR; 171 } 172 173 }
以上就是org.apache.httpcomponents:httpclient 工具类的详细内容,更多请关注其它相关文章!