先引入包:
<!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.12</version>
</dependency>
HttpGet請求:時間設置爲90秒(90000).
public static HttpResponse sendGet(String targetUrl, String contentType) {
HttpResponse response = null;
try {
HttpClient httpClient = HttpClientBuilder.create().build();
HttpGet httpGet = new HttpGet(targetUrl);
httpGet.setConfig(RequestConfig.custom().setConnectionRequestTimeout(connectionRequestTimeout)
.setConnectTimeout(connectTimeout).setSocketTimeout(socketTimeout).build());
httpGet.addHeader("Content-Type", contentType);
response = httpClient.execute(httpGet);
} catch (ClientProtocolException e) {
throw new BusinessException(e);
} catch (IOException e) {
throw new BusinessException(e);
}
return response;
}
Post請求:Map參數
public static HttpResponse sendPost(String targetUrl, Map<String, String> sendMsgMaps, String enCoding) {
CloseableHttpClient httpClient = null;
HttpPost httpPost = null;
HttpResponse response = null;
try {
//add interceptor
HttpRequestInterceptor itcp=new CallChainHttpClientRequestFilter();
HttpClientBuilder.create().addInterceptorLast(itcp).build();
if (targetUrl.startsWith("https")) {
httpClient = enableSSL();
}
httpPost = new HttpPost(targetUrl);
httpPost.setConfig(RequestConfig.custom().setConnectionRequestTimeout(connectionRequestTimeout)
.setConnectTimeout(connectTimeout).setSocketTimeout(socketTimeout).build());
List<NameValuePair> vals = new ArrayList<NameValuePair>();
Set<String> names = sendMsgMaps.keySet();
NameValuePair nvp = null;
for (String name : names) {
nvp = new BasicNameValuePair(name, sendMsgMaps.get(name));
vals.add(nvp);
}
UrlEncodedFormEntity uefEntity;
uefEntity = new UrlEncodedFormEntity(vals, enCoding);
httpPost.setEntity(uefEntity);
response = httpClient.execute(httpPost);
} catch (ClientProtocolException e) {
throw new BusinessException(e);
} catch (IOException e) {
throw new BusinessException(e);
} finally {
if (null != httpPost) {
httpPost.abort();
}
try {
if (null != httpClient) {
httpClient.close();
}
} catch (IOException e) {
throw new BusinessException(e);
}
}
return response;
}
private static CloseableHttpClient enableSSL() {
CloseableHttpClient httpClient = null;
try {
SSLContext sslcontext = SSLContext.getInstance("TLS");
sslcontext.init(null, new TrustManager[] { truseAllManager }, null);
SSLConnectionSocketFactory sslcsf = new SSLConnectionSocketFactory(sslcontext, null, null,
hostnameVerifier);
RegistryBuilder<ConnectionSocketFactory> registryBuilder = RegistryBuilder
.<ConnectionSocketFactory>create();
Registry<ConnectionSocketFactory> registry = registryBuilder.register("https", sslcsf).build();
PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(registry);
//add interceptor
HttpRequestInterceptor itcp=new CallChainHttpClientRequestFilter();
httpClient = HttpClientBuilder.create().addInterceptorLast(itcp).setConnectionManager(connManager).build();
return httpClient;
} catch (Exception e) {
throw new BusinessException(e);
}
}
Post請求:參數是String
HttpEntity httpEntity = new StringEntity(str, enCoding);
public static Map sendPostStr(String targetUrl, String str, String enCoding, String contentType) {
HttpResponse response = null;
CloseableHttpClient httpClient = null;
HttpPost httpPost = null;
Map ret = new HashMap();
try {
//add interceptor
HttpRequestInterceptor itcp=new CallChainHttpClientRequestFilter();
httpClient = HttpClientBuilder.create().addInterceptorLast(itcp).build();
if (targetUrl.startsWith("https")) {
httpClient = enableSSL();
}
httpPost = new HttpPost(targetUrl);
httpPost.setConfig(RequestConfig.custom().setConnectionRequestTimeout(connectionRequestTimeout)
.setConnectTimeout(connectTimeout).setSocketTimeout(socketTimeout).build());
HttpEntity httpEntity = new StringEntity(str, enCoding);
httpPost.addHeader("Content-Type", contentType);
httpPost.setEntity(httpEntity);
response = httpClient.execute(httpPost);
// 調用request的abort方法
String code = response.getStatusLine().getStatusCode() + "";
String body = "";
ret.put("code", code);
if ("200".equals(code)) {
body = EntityUtils.toString(response.getEntity());
ret.put("body", body);
} else if ("302".equals(code)) {
ret.put("location", response.getFirstHeader("Location").getValue());
}
} catch (ClientProtocolException e) {
throw new BusinessException(e);
} catch (IOException e) {
throw new BusinessException(e);
} finally {
if (null != httpPost) {
httpPost.abort();
}
if (null != httpClient) {
httpClient.getConnectionManager().shutdown();
}
}
return ret;
}
Post請求:參數是NameValuePair數組
HttpEntity httpEntity = new UrlEncodedFormEntity(Arrays.asList(nameValuePairs));
public static Map<String, Object> sendPostNameValuePair(String targetUrl, NameValuePair[] nameValuePairs, String contentType) throws IOException {
HttpResponse response = null;
CloseableHttpClient httpClient = null;
HttpPost httpPost = null;
Map<String, Object> ret = new HashMap<String, Object>();
try {
//add interceptor
HttpRequestInterceptor itcp=new CallChainHttpClientRequestFilter();
httpClient = HttpClientBuilder.create().addInterceptorLast(itcp).build();
if (targetUrl.startsWith("https")) {
httpClient = enableSSL();
}
httpPost = new HttpPost(targetUrl);
httpPost.setConfig(RequestConfig.custom().setConnectionRequestTimeout(connectionRequestTimeout)
.setConnectTimeout(connectTimeout).setSocketTimeout(socketTimeout).build());
HttpEntity httpEntity = new UrlEncodedFormEntity(Arrays.asList(nameValuePairs));
httpPost.addHeader("Content-Type", contentType);
httpPost.setEntity(httpEntity);
response = httpClient.execute(httpPost);
// 調用request的abort方法
String code = response.getStatusLine().getStatusCode() + "";
String body = "";
ret.put("code", code);
ret.put("allHeaders", response.getAllHeaders());
if ("200".equals(code)) {
body = EntityUtils.toString(response.getEntity());
ret.put("body", body);
} else if ("302".equals(code)) {
ret.put("location", response.getFirstHeader("Location").getValue());
}
} catch (IOException e) {
throw e;
} finally {
if (null != httpPost) {
httpPost.abort();
}
if (null != httpClient) {
httpClient.getConnectionManager().shutdown();
}
}
return ret;
}
POST請求:帶證書
public static CloseableHttpClient getCertHttpClient(String apiclientCertPath, String password) {
CloseableHttpClient httpClient;
try {
// 指定讀取證書格式爲PKCS12
KeyStore keyStore = KeyStore.getInstance("PKCS12");
// 讀取本機存放的PKCS12證書文件
InputStream instream =Thread.currentThread().getClass().getResourceAsStream(apiclientCertPath);
// 指定PKCS12的密碼(商戶ID)
keyStore.load(instream, password.toCharArray());
SSLContext sslcontext = SSLContexts.custom().loadKeyMaterial(keyStore, password.toCharArray()).build();
// Allow TLSv1 protocol only
SSLConnectionSocketFactory sslcsf = new SSLConnectionSocketFactory(sslcontext, new String[] { "TLSv1" },
null, hostnameVerifier);
// 構建客戶端
httpClient = HttpClientBuilder.create().setSSLSocketFactory(sslcsf).build();
return httpClient;
} catch (KeyStoreException e) {
throw new BusinessException(e);
} catch (FileNotFoundException e) {
throw new BusinessException(e);
} catch (NoSuchAlgorithmException e) {
throw new BusinessException(e);
} catch (CertificateException e) {
throw new BusinessException(e);
} catch (IOException e) {
throw new BusinessException(e);
} catch (KeyManagementException e) {
throw new BusinessException(e);
} catch (UnrecoverableKeyException e) {
throw new BusinessException(e);
}
}
public static HttpResponse sendPostStrWithCert(String apiclientCertPath, String password, String targetUrl,
String str, String enCoding, String contentType) {
HttpResponse response = null;
CloseableHttpClient httpClient = null;
HttpPost httpPost = null;
try {
httpClient = getCertHttpClient(apiclientCertPath, password);
if (null != httpClient) {
httpPost = new HttpPost(targetUrl);
httpPost.setConfig(RequestConfig.custom().setConnectionRequestTimeout(connectionRequestTimeout)
.setConnectTimeout(connectTimeout).setSocketTimeout(socketTimeout).build());
HttpEntity httpEntity = new StringEntity(str, enCoding);
httpPost.addHeader("Content-Type", contentType);
httpPost.setEntity(httpEntity);
response = httpClient.execute(httpPost);
}
} catch (ClientProtocolException e) {
throw new BusinessException(e);
} catch (IOException e) {
throw new BusinessException(e);
} finally {
if (null != httpPost) {
httpPost.abort();
}
try {
if (null != httpClient) {
httpClient.close();
}
} catch (IOException e) {
throw new BusinessException(e);
}
}
return response;
}