1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335
| import org.apache.commons.lang3.StringUtils; import org.apache.http.HttpEntity; import org.apache.http.HttpStatus; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.config.RequestConfig; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.methods.HttpUriRequest; import org.apache.http.client.utils.URIBuilder; import org.apache.http.config.Registry; import org.apache.http.config.RegistryBuilder; import org.apache.http.conn.socket.ConnectionSocketFactory; import org.apache.http.conn.socket.PlainConnectionSocketFactory; import org.apache.http.conn.ssl.SSLConnectionSocketFactory; import org.apache.http.conn.ssl.TrustSelfSignedStrategy; import org.apache.http.entity.ContentType; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.DefaultHttpRequestRetryHandler; import org.apache.http.impl.client.HttpClients; import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; import org.apache.http.message.BasicNameValuePair; import org.apache.http.ssl.SSLContextBuilder; import org.apache.http.util.EntityUtils;
import java.io.IOException; import java.io.UnsupportedEncodingException; import java.net.URI; import java.net.URISyntaxException; import java.nio.charset.Charset; import java.security.KeyManagementException; import java.security.KeyStoreException; import java.security.NoSuchAlgorithmException; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.concurrent.TimeUnit;
@SuppressWarnings("all") public class HttpUtils { private static final String DEFAULT_CHARSET = "UTF-8"; private static final String DEFAULT_POST_CONTENTTYPE = "application/x-www-form-urlencoded"; private static final String JSON_CONTENTTYPE = "application/json"; private static final int REQUEST_TIMEOUT = 60 * 1000; private static final int SO_TIMEOUT = 60 * 1000; private static RequestConfig requestConfig; private static PoolingHttpClientConnectionManager poolConnManager = null;
private static CloseableHttpClient httpClient;
private static String userAgent;
static { requestConfig = RequestConfig.custom() .setConnectionRequestTimeout(REQUEST_TIMEOUT) .setConnectTimeout(SO_TIMEOUT) .build(); userAgent = "Mozilla/5.0 (Windows; U; Windows NT 6.1; rv:2.2) Gecko/20110201";
try { SSLContextBuilder builder = new SSLContextBuilder(); builder.loadTrustMaterial(null, new TrustSelfSignedStrategy()); SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory( builder.build()); Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create().register( "http", PlainConnectionSocketFactory.getSocketFactory()).register( "https", sslsf).build(); poolConnManager = new PoolingHttpClientConnectionManager( socketFactoryRegistry); poolConnManager.setMaxTotal(1000); poolConnManager.setDefaultMaxPerRoute(20); int socketTimeout = 10000; int connectTimeout = 10000; int connectionRequestTimeout = 10000; requestConfig = RequestConfig.custom().setConnectionRequestTimeout( connectionRequestTimeout).setSocketTimeout(socketTimeout).setConnectTimeout( connectTimeout).build();
httpClient = getConnection();
} catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (KeyStoreException e) { e.printStackTrace(); } catch (KeyManagementException e) { e.printStackTrace(); }
}
public static String doGet(String url, Map<String, Object> parameterMap) { long start = System.currentTimeMillis(); CloseableHttpClient client = buildClient(); String uri = buildURI(url, parameterMap); String res = getEntityString(client, new HttpGet(uri), null); return res; }
public static String doGetForceResCharset(String url, Map<String, Object> parameterMap, String resCharSet) { CloseableHttpClient client = buildClient(); String uri = buildURI(url, parameterMap); Charset charSet = Charset.forName(resCharSet); return getEntityString(client, new HttpGet(uri), charSet); }
public static String doPost(String url, Map<String, Object> parameterMap) { return doPostWithEncoding(url, parameterMap, DEFAULT_CHARSET); }
public static String doPost(String url, Map<String, Object> headerMap, String json) { return doPostJsonWithHeader(url, headerMap, json, DEFAULT_CHARSET); }
public static String doPost(String url, String json) { return doPostJsonWithCharset(url, json, DEFAULT_CHARSET); }
public static String doPostJsonWithCharset(String url, String json, String charset) { return getEntityString(buildClient(), buildHttpPost(url, null, null, charset, JSON_CONTENTTYPE, json), null); }
public static String doPostJsonWithHeader(String url, Map<String, Object> headerMap, String json, String charset) { return getEntityString(buildClient(), buildHttpPost(url, headerMap, null, charset, JSON_CONTENTTYPE, json), null); }
public static String doPostWithEncoding(String url, Map<String, Object> parameterMap, String charset) { CloseableHttpClient client = buildClient(); HttpPost post = buildHttpPost(url, null, parameterMap, charset, null, null); return getEntityString(client, post, null); }
private static HttpPost buildHttpPost(String url, Map<String, Object> headerMap, Map<String, Object> parameterMap, String charset, String contentType, String body) {
HttpPost post = new HttpPost(url); charset = null == charset ? DEFAULT_CHARSET : charset; contentType = null == contentType ? DEFAULT_POST_CONTENTTYPE : contentType; post.setHeader("Content-Type", contentType + "; charset=" + charset); if (null != headerMap) { if (null != headerMap.get("token")) { post.setHeader("token", headerMap.get("token").toString()); } if (null != headerMap.get("appKey")) { post.setHeader("appKey", headerMap.get("appKey").toString()); } } if (null != body && contentType == "application/json" && null == parameterMap) { StringEntity stringEntity = new StringEntity(body, charset); post.setEntity(stringEntity); } else { try { UrlEncodedFormEntity entity = new UrlEncodedFormEntity(mapToNameValueList(parameterMap), charset); post.setEntity(entity); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } } return post; }
private static CloseableHttpClient buildClient() { return httpClient; }
private static String buildURI(String url, Map<String, Object> parameterMap) { URIBuilder builder; try { builder = new URIBuilder(url); if (null != parameterMap) { for (String key : parameterMap.keySet()) { builder.addParameter(key, parameterMap.get(key).toString()); } } URI uri = builder.build(); return uri.toString(); } catch (URISyntaxException e) { e.printStackTrace(); } return StringUtils.EMPTY; }
private static String getEntityString(CloseableHttpClient client, HttpUriRequest request, Charset forceCharset) { CloseableHttpResponse response = null; String res = ""; request.setHeader("Connection", "close"); try { response = client.execute(request);
if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) { request.abort(); } else { HttpEntity entity = response.getEntity(); ContentType contentType = ContentType.getOrDefault(entity); Charset charSet = contentType.getCharset(); charSet = ensureCharset(charSet, forceCharset); res = EntityUtils.toString(entity, charSet); } } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { try { if (response != null) response.close(); } catch (IOException e) { e.printStackTrace(); } client.getConnectionManager().closeIdleConnections(0, TimeUnit.SECONDS); } return res; }
private static Charset ensureCharset(Charset charSet, Charset forceCharset) { if (forceCharset != null) charSet = forceCharset; if (charSet == null) charSet = Charset.forName(DEFAULT_CHARSET); return charSet; }
public static CloseableHttpClient getConnection() { CloseableHttpClient httpClient = HttpClients.custom() .setConnectionManager(poolConnManager) .setDefaultRequestConfig(requestConfig) .setRetryHandler(new DefaultHttpRequestRetryHandler(0, false)) .build();
return httpClient; }
private static List<BasicNameValuePair> mapToNameValueList(Map<String, Object> parameterMap) { List<BasicNameValuePair> list = new ArrayList<BasicNameValuePair>(); for (String key : parameterMap.keySet()) { list.add(new BasicNameValuePair(key, parameterMap.get(key).toString())); } return list; } }
|