話不多說,直接上代碼
public class HttpRequestUtils {
private static final Logger logger = LoggerFactory.getLogger(HttpRequestUtils.class);
private static final String CHARSET_UTF_8 = "UTF-8";
private static final String HTTP = "http";
private static final String HTTPS = "https";
private static SSLConnectionSocketFactory sslsf = null;
private static PoolingHttpClientConnectionManager cm = null;
private static SSLContextBuilder builder = null;
static {
try {
builder = new SSLContextBuilder();
// 全部信任 不做身份鑑定
builder.loadTrustMaterial(null, new TrustStrategy() {
@Override
public boolean isTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
return true;
}
});
sslsf = new SSLConnectionSocketFactory(builder.build(),
new String[] { "SSLv2Hello", "SSLv3", "TLSv1", "TLSv1.2" }, null, NoopHostnameVerifier.INSTANCE);
Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory> create()
.register(HTTP, new PlainConnectionSocketFactory()).register(HTTPS, sslsf).build();
cm = new PoolingHttpClientConnectionManager(registry);
cm.setMaxTotal(1000);// max connection
} catch (Exception e) {
logger.error("ssl init error", e);
}
}
private HttpRequestUtils() {
}
public static String postWithStringParam(String url, Object toJson) {
return postWithStringParam(url, JsonUtils.objectToJson(toJson));
}
public static String postWithStringParam(String url, String stringParam) {
logger.info("url:{}, param:{}", url, stringParam);
CloseableHttpClient httpClient = null;
try {
int connectionTimeout = Integer.parseInt(getProperty("tbp.resource.web.connectionTimeout", "60000")) ;
int timeout = Integer.parseInt(getProperty("tbp.resource.web.timeout", "60000"));
int socketTimeout = Integer.parseInt(getProperty("tbp.resource.web.socketTimeout", "60000"));
httpClient = HttpClients.custom().disableAutomaticRetries().build();
HttpPost httpPost = new HttpPost(url);
RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(connectionTimeout)
.setConnectionRequestTimeout(timeout).setSocketTimeout(socketTimeout).build();
if(!StringUtils.isEmpty(stringParam)){
StringEntity entity = new StringEntity(stringParam, CHARSET_UTF_8);// 解決中文亂碼問題
entity.setContentEncoding(CHARSET_UTF_8);
entity.setContentType("application/json");
httpPost.setEntity(entity);
}
httpPost.setConfig(requestConfig);
return httpClient.execute(httpPost, new ResponseHandler<String>() {
@Override
public String handleResponse(HttpResponse response) throws IOException {
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode == HttpStatus.SC_OK || statusCode == HttpStatus.SC_INTERNAL_SERVER_ERROR) {
return EntityUtils.toString(response.getEntity(), CHARSET_UTF_8);
}
throw new IOException(response.toString());
}
});
} catch (IOException e) {
logger.error("HttpRequestUtils.postWithStringParam error,url:" + url + ",stringParam:" + stringParam, e);
throw new ResourceRuntimeException("網絡繁忙,請稍後再試.");
} finally {
HttpClientUtils.closeQuietly(httpClient);
}
}
/**
*
* 描述:(取資源文件裏面的信息). <br/>
*
* @author 80000449 2018年11月6日下午8:28:00
*
* @param key
* @param defualtValue
* @return
*/
private static String getProperty(String key, String defualtValue){
return PropertiesManager.instance().getString(key, defualtValue);
}
/**
* 發送 SSL GET 請求(HTTPS)
*
* @param url
* @return
*/
public static String getSSL(String url) {
CloseableHttpClient httpClient = null;
try {
httpClient = HttpClients.custom().setSSLSocketFactory(sslsf).setConnectionManager(cm)
.setConnectionManagerShared(true).disableAutomaticRetries().build();
HttpGet httpGet = new HttpGet(url);
return httpClient.execute(httpGet, new ResponseHandler<String>() {
@Override
public String handleResponse(HttpResponse response) throws IOException {
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode == HttpStatus.SC_OK || statusCode == HttpStatus.SC_INTERNAL_SERVER_ERROR) {
return EntityUtils.toString(response.getEntity(), CHARSET_UTF_8);
}
return null;
}
});
} catch (IOException e) {
logger.error("HttpRequestUtils.getSSL error,url:" + url, e);
throw new ResourceRuntimeException(e);
} finally {
HttpClientUtils.closeQuietly(httpClient);
}
}
/**
* 發送 SSL POST 請求(HTTPS)
*
* @param url
* @param toJson
* @return
*/
public static String postSSLWithJsonParam(String url, Object toJson) {
return postSSL(url, JsonUtils.objectToJson(toJson));
}
/**
* 發送 SSL POST 請求(HTTPS)
*
* @param url
* @param stringParam
* @return
*/
public static String postSSL(String url,String stringParam) {
CloseableHttpClient httpClient = null;
try {
httpClient = HttpClients.custom().setSSLSocketFactory(sslsf).setConnectionManager(cm)
.setConnectionManagerShared(true).disableAutomaticRetries().build();
HttpPost httpPost = new HttpPost(url);
StringEntity entity = new StringEntity(stringParam, CHARSET_UTF_8);// 解決中文亂碼問題
entity.setContentEncoding(CHARSET_UTF_8);
entity.setContentType("application/json");
httpPost.setEntity(entity);
return httpClient.execute(httpPost, new ResponseHandler<String>() {
@Override
public String handleResponse(HttpResponse response) throws IOException {
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode == HttpStatus.SC_OK || statusCode == HttpStatus.SC_INTERNAL_SERVER_ERROR) {
return EntityUtils.toString(response.getEntity(), CHARSET_UTF_8);
}
return null;
}
});
} catch (IOException e) {
logger.error("HttpRequestUtils.postSSL error,url:" + url, e);
throw new ResourceRuntimeException(e);
} finally {
HttpClientUtils.closeQuietly(httpClient);
}
}
}
使用方式
String result = HttpRequestUtils.postWithStringParam(taskUrl+"/fullDayResultService/fullDayActualDistance", params);// params 不傳可爲null