https封装工具类

来源:互联网 发布:研究生做软件测试待遇 编辑:程序博客网 时间:2024/06/05 19:15
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();
   }
   
}
0 0
原创粉丝点击