https封裝工具類
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.SocketTimeoutException;
import java.net.URISyntaxException;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.UnrecoverableKeyException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import javax.net.ssl.SSLContext;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.HttpException;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
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.utils.URIBuilder;
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.conn.ConnectionPoolTimeoutException;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLContexts;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.FormBodyPart;
import org.apache.http.entity.mime.HttpMultipartMode;
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.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
class AnyTrustStrategy implements TrustStrategy{
public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
return true;
}
}
public class HttpsRequest{
private static final Log log= LogFactory.getLog(HttpsRequest.class);
private static String keystorePath=UploadTransfer.keyStoreLocalFilePath;//載入本地的證書進行https加密傳輸
private static final String keystorePathName=UploadTransfer.keyStoreLocalFilePathName;//名稱
private static final String keystorePassword=UploadTransfer.keyStoreLocalFilePassword;//設定證書密碼
public static String defaultEncoding= "utf-8";
private static int bufferSize= 1024;
//表示請求器是否已經做了初始化工作
private boolean hasInit = false;
//連線超時時間,預設10秒
private int socketTimeout = 10000;
//傳輸超時時間,預設30秒
private int connectTimeout = 30000;
//請求器的配置
private RequestConfig requestConfig;
//HTTP請求器
private CloseableHttpClient httpClient;
public HttpsRequest() throws UnrecoverableKeyException, KeyManagementException, NoSuchAlgorithmException, KeyStoreException, IOException {
keystorePath = this.getClass().getResource("/").getPath()+keystorePathName;
init();
}
private void init() throws IOException, KeyStoreException, UnrecoverableKeyException, NoSuchAlgorithmException, KeyManagementException {
KeyStore keyStore = KeyStore.getInstance("PKCS12");
FileInputStream instream = new FileInputStream(new File(keystorePath));//載入本地的證書進行https加密傳輸
try {
keyStore.load(instream, keystorePassword.toCharArray());//設定證書密碼 //TODO
} catch (CertificateException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} finally {
instream.close();
}
// Trust own CA and all self-signed certs
SSLContext sslcontext = SSLContexts.custom()
.loadKeyMaterial(keyStore, keystorePassword.toCharArray()).loadTrustMaterial(null, new AnyTrustStrategy())//信任所有伺服器
.build();
// Allow TLSv1 protocol only
try{
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
sslcontext,
new String[]{"TLSv1"},
null,
SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
httpClient = HttpClients.custom()
.setSSLSocketFactory(sslsf)
.build();
//根據預設超時限制初始化requestConfig
requestConfig = RequestConfig.custom().setSocketTimeout(socketTimeout).setConnectTimeout(connectTimeout).build();
hasInit = true;
}catch(Exception e){
e.printStackTrace();
}
}
/**
* 多塊Post請求
* @param url 請求url
* @param queryParams 請求頭的查詢引數
* @param formParts post表單的引數,支援字串-檔案(FilePart)和字串-字串(StringPart)形式的引數
* @param maxCount 最多嘗試請求的次數
* @return
* @throws URISyntaxException
* @throws ClientProtocolException
* @throws HttpException
* @throws IOException
*/
public String sendPost(String url, File xmlFile) throws IOException, KeyStoreException, UnrecoverableKeyException, NoSuchAlgorithmException, KeyManagementException {
if (!hasInit) {
init();
}
String result = null;
HttpPost httpPost = new HttpPost(url);
List<FormBodyPart> formParts = new ArrayList<FormBodyPart>();
formParts.add(new FormBodyPart("signFile", new FileBody(xmlFile)));
//填入表單引數
if (formParts!=null && !formParts.isEmpty()){
MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create();
entityBuilder = entityBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
for (FormBodyPart formPart : formParts) {
entityBuilder = entityBuilder.addPart(formPart.getName(), formPart.getBody());
}
httpPost.setEntity(entityBuilder.build());
}
//設定請求器的配置
httpPost.setConfig(requestConfig);
System.out.println(("executing request" + httpPost.getRequestLine()));
try {
HttpResponse response = httpClient.execute(httpPost);
if(response.getStatusLine().getStatusCode()==200){
return EntityUtils.toString(response.getEntity(),"UTF-8");
}
return null;
} catch (ConnectionPoolTimeoutException e) {
e.printStackTrace();
} catch (ConnectTimeoutException e) {
e.printStackTrace();
} catch (SocketTimeoutException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
httpPost.abort();
}
return result;
}
/**
* do post
* @param url
* @param params
* @throws Exception
*/
public void post(String url, String params) throws Exception {
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new StringEntity(params,
ContentType.APPLICATION_JSON));
CloseableHttpResponse resp = httpClient.execute(httpPost);
// System.out.println(resp.getStatusLine());
InputStream respIs = resp.getEntity().getContent();
String content = convertStreamToString(respIs);
System.out.println(content);
EntityUtils.consume(resp.getEntity());
}
/**
* 基本的Post請求
* @param url 請求url
* @param queryParams 請求頭的查詢引數
* @param formParams post表單的引數
* @return
* @throws URISyntaxException
* @throws IOException
* @throws ClientProtocolException
*/
public HttpResponse doPost(String url, Map<String, String> queryParams, Map<String, String> formParams) throws URISyntaxException, ClientProtocolException, IOException{
HttpPost httpPost = new HttpPost();
URIBuilder builder = new URIBuilder(url);
//填入查詢引數
if (queryParams!=null && !queryParams.isEmpty()){
builder.setParameters(HttpsRequest.paramsConverter(queryParams));
}
httpPost.setURI(builder.build());
//填入表單引數
if (formParams!=null && !formParams.isEmpty()){
httpPost.setEntity(new UrlEncodedFormEntity(HttpsRequest.paramsConverter(formParams)));
}
return httpClient.execute(httpPost);
}
public InputStream doGet(String url) throws URISyntaxException, ClientProtocolException, IOException{
HttpResponse response= this.doGet(url, null);
return response!=null ? response.getEntity().getContent() : null;
}
public String doGetForString(String url) throws URISyntaxException, ClientProtocolException, IOException{
return HttpsRequest.readStream(this.doGet(url), null);
}
public InputStream doGetForStream(String url, Map<String, String> queryParams) throws URISyntaxException, ClientProtocolException, IOException{
HttpResponse response= this.doGet(url, queryParams);
return response!=null ? response.getEntity().getContent() : null;
}
public String doGetForString(String url, Map<String, String> queryParams) throws URISyntaxException, ClientProtocolException, IOException{
return HttpsRequest.readStream(this.doGetForStream(url, queryParams), null);
}
/**
* 基本的Get請求
* @param url 請求url
* @param queryParams 請求頭的查詢引數
* @return
* @throws URISyntaxException
* @throws IOException
* @throws ClientProtocolException
*/
public HttpResponse doGet(String url, Map<String, String> queryParams) throws URISyntaxException, ClientProtocolException, IOException{
HttpGet gm = new HttpGet();
URIBuilder builder = new URIBuilder(url);
//填入查詢引數
if (queryParams!=null && !queryParams.isEmpty()){
builder.setParameters(HttpsRequest.paramsConverter(queryParams));
}
gm.setURI(builder.build());
return httpClient.execute(gm);
}
public InputStream doPostForStream(String url, Map<String, String> queryParams) throws URISyntaxException, ClientProtocolException, IOException {
HttpResponse response = this.doPost(url, queryParams, null);
return response!=null ? response.getEntity().getContent() : null;
}
public String doPostForString(String url, Map<String, String> queryParams) throws URISyntaxException, ClientProtocolException, IOException {
return HttpsRequest.readStream(this.doPostForStream(url, queryParams), null);
}
public InputStream doPostForStream(String url, Map<String, String> queryParams, Map<String, String> formParams) throws URISyntaxException, ClientProtocolException, IOException{
HttpResponse response = this.doPost(url, queryParams, formParams);
return response!=null ? response.getEntity().getContent() : null;
}
public String doPostRetString(String url, Map<String, String> queryParams, Map<String, String> formParams) throws URISyntaxException, ClientProtocolException, IOException{
return HttpsRequest.readStream(this.doPostForStream(url, queryParams, formParams), null);
}
/**
* 設定連線超時時間
*
* @param socketTimeout 連線時長,預設10秒
*/
public void setSocketTimeout(int socketTimeout) {
socketTimeout = socketTimeout;
resetRequestConfig();
}
/**
* 設定傳輸超時時間
*
* @param connectTimeout 傳輸時長,預設30秒
*/
public void setConnectTimeout(int connectTimeout) {
connectTimeout = connectTimeout;
resetRequestConfig();
}
private void resetRequestConfig(){
requestConfig = RequestConfig.custom().setSocketTimeout(socketTimeout).setConnectTimeout(connectTimeout).build();
}
/**
* 允許商戶自己做更高階更復雜的請求器配置
*
* @param requestConfig 設定HttpsRequest的請求器配置
*/
public void setRequestConfig(RequestConfig requestConfig) {
requestConfig = requestConfig;
}
private static List<NameValuePair> paramsConverter(Map<String, String> params){
List<NameValuePair> nvps = new LinkedList<NameValuePair>();
Set<Entry<String, String>> paramsSet= params.entrySet();
for (Entry<String, String> paramEntry : paramsSet) {
nvps.add(new BasicNameValuePair(paramEntry.getKey(), paramEntry.getValue()));
}
return nvps;
}
public static String readStream(InputStream in, String encoding){
if (in == null){
return null;
}
try {
InputStreamReader inReader= null;
if (encoding == null){
inReader= new InputStreamReader(in, defaultEncoding);
}else{
inReader= new InputStreamReader(in, encoding);
}
char[] buffer= new char[bufferSize];
int readLen= 0;
StringBuffer sb= new StringBuffer();
while((readLen= inReader.read(buffer))!=-1){
sb.append(buffer, 0, readLen);
}
inReader.close();
return sb.toString();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
public static String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
}