1. 程式人生 > >https封裝工具類

https封裝工具類

package


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();
   }
   
}

相關推薦

https封裝工具

package import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.In

swift3.0請求https封裝工具(get請求和post請求)

1.首先工具類內部需要遵守URLSessionDataDelegate代理 2.實現代理方法程式碼如下: func urlSession(_ session:URLSession, didRe

如何呼叫封裝工具呼叫網上介面查詢工作日

如何呼叫封裝工具類呼叫網上介面查詢工作日 這裡的編輯器是STS,用的springboot整合環境; 先引進pom.xml依賴包 <?xml version="1.0" encoding="UTF-8"?> <project xml

HIbernate -----封裝 工具 utils(configration---建立sessionFactory--獲得session程式碼重複,封裝程式碼)

package com.itheima.utils; import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration; import org.hibernate.classic.Session; //完成

微信小程式:request請求封裝工具

修改過的封裝請求: header: {'Content-Type': 'application/json'},  防止引數中敏感字元丟失的問題 header: {'Content-Type': 'application/x-www-form-urlencoded'}, 

HttpUrlConnection+圖片載入+工具+介面回撥+單例+AsyncTask封裝工具

1.MainActivity頁面 package com.example.httpurlconnection; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import andro

dljd_011_jdbc再次封裝工具_把數據庫的相關信息寫到配置文件中,減低代碼的耦合度

man 數據庫工具類 () version 數據庫配置 測試 loader connect not 一、將連接數據庫所需的相關信息寫入到配置文件、通過讀取配置文件來獲取數據庫的相關信息 package edu.aeon.aeonutils; import jav

用hibernate封裝工具中的查詢方法

 可以將以下的方法整合到工具類中,用於以後的使用 public List query(String hql,Object...object){//使用這個類的時候hql語句形式:from 類 where ... //讀取總的配置檔案 Configuratio

Json結果集封裝工具-使用java的Map

/** * Title: Json * Description: Json結果集封裝工具類* @author zhaoxuehong * @date 2018年11月5日上午9:15:55 */public class Json { /** * * @param status 狀態碼 * @param ms

BeanUtils資料封裝工具的使用

Java程式碼: package com.java.domain; public class Person { private String name; private int age; private String gender; private String

微信開發的Http或Https常用工具

前不久寫了幾篇有關微信定製開發的文章並整理成了專題,裡面所有的文件都提到了CommonUtil這個工具類,關於這個工具類原本有寫但是不是每篇部落格都有,所以就有人找我要這個工具類,評論裡也有好多人說不知道這個工具類怎麼寫,因此針對這些疑問就特意給大家貼一下程式碼 1  由於

單機版 RedisPoolUtil({基本操作封裝工具})【一】

<!--整合的RedisJAR--> <!--引入jedis需的jar包--> <dependency> <groupId>redis.clients</groupId> <artifactId>jedis&

單機版 JedisUtil({基本操作封裝工具})【二】

<!--整合的RedisJAR--> <!--引入jedis需的jar包--> <dependency> <groupId>redis.clients</groupId> <artifactId>jedis&

單機版 RedisUtils({基本操作封裝工具})【三】

<!--整合的RedisJAR--> <!--引入jedis需的jar包--> <dependency> <groupId>redis.clients</groupId> <artifactId>jedis&

glide封裝工具

Google圖片載入庫Glide的簡單封裝GlideUtils 因為專案裡用的Glide的地方比較多,所有簡單的封裝了以下,其實也沒什麼,就是寫了個工具類,但是還是要把基礎說下 Glide的Github Glide簡單配置 Glide有三種整合的方式 1.

ImageLoder封裝工具..

public class ImageLoaderutils {     //初使化     public static void initImageLoader(Context context){         //自定義磁碟快取路徑  系統預設的快取路徑 sd...&l

httpclient封裝工具

前言 在日常開發中,我們經常需要通過http協議去呼叫網路內容,雖然java自身提供了net相關工具包,但是其靈活性和功能總是不如人意,於是有人專門搞出一個httpclient類庫,來方便進行Http操作。對於httpcore的原始碼研究,我們可能並沒有達到這

Redis封裝工具

引用到的jedis的封裝類,然後又加了一層封裝 import java.util.List; import java.util.Map; import java.util.Set; import redis.clients.jedis.JedisCommands; i

http https請求工具

1 import java.io.BufferedReader; 2 import java.io.InputStream; 3 import java.io.InputStreamReader; 4 import java.io.OutputStream;

OkHttp網路連線封裝工具以及json轉換

public class OkHttpUtils { private static final String TAG = "OkHttpUtils"; private static OkHttpUtils mInstance;