欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

httpclient4.2 https post接口linux使用TLSv1.2协议

程序员文章站 2022-05-07 08:20:43
...

1. SSLClient 继承DefaultHttpClient ,设定TLSv1.2,https允许所有hostname

import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.impl.client.DefaultHttpClient;  

public class SSLClient extends DefaultHttpClient {  
        public SSLClient() throws Exception {  
            super();  
            SSLContext ctx = SSLContext.getInstance("TLSv1.2");  
            X509TrustManager tm = new X509TrustManager() {

				@Override
				public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
					// TODO Auto-generated method stub
					
				}

				@Override
				public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
					// TODO Auto-generated method stub
					
				}

				@Override
				public X509Certificate[] getAcceptedIssuers() {
					// TODO Auto-generated method stub
					return null;
				}  
            };  
            ctx.init(null, new TrustManager[] { tm }, null);  
            org.apache.http.conn.ssl.SSLSocketFactory ssf = new org.apache.http.conn.ssl.SSLSocketFactory(ctx,  
                    org.apache.http.conn.ssl.SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);  
            ClientConnectionManager ccm = this.getConnectionManager();  
            SchemeRegistry sr = ccm.getSchemeRegistry();  
            sr.register(new Scheme("https", 443, ssf));  
        }  
    }  

 2. https使用SSLClient 创建client

import java.io.InputStream;

import java.net.URI;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.net.ssl.X509TrustManager;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIUtils;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.params.CoreProtocolPNames;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

public class HttpSSLClientUtil {

/** 发送POST   支持http、https
     * @param url        post地址
     * @param paramMap   要传递的参数封装成Map
     * @param num        如果post失败连续post次数
     * @param return     返回 fail\0\..:失败 ;1:成功  ..其他具体消息
     */
    public static String sendPost(String url,Map<String, String> paramMap){
        String returnmsg="";
    try {
           //封装参数
           List<NameValuePair> parameters = new ArrayList<NameValuePair>();
           if(paramMap!=null&&paramMap.keySet()!=null){
                for(String key:paramMap.keySet()){
                    parameters.add(new BasicNameValuePair(key,paramMap.get(key)));
                }
            }
           //创建UrlEncodedFormEntity对象
           UrlEncodedFormEntity formEntiry = new UrlEncodedFormEntity(parameters,"UTF-8");
           if(url.startsWith("https")){
               returnmsg=sendPostHttps(url,formEntiry,paramMap);
           }else{
               returnmsg=sendPostHttp(url,formEntiry,paramMap);
           }
       }catch(Exception e){
          e.printStackTrace();
       }
     return returnmsg;
   }
    
   //发送http请求
   private static String sendPostHttp(String url, UrlEncodedFormEntity formEntiry,Map<String, String> paramMap){
        // 发送请求
        HttpClient client = new DefaultHttpClient();
        client.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT,10000);//连接时间

        client.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT,10000);//数据传输时间
        String returnmsg="fail"; //失败
    try {
            //实例化HTTP POST方法
            HttpPost postmethod = new HttpPost(url);
            postmethod.addHeader("Content-Type","application/x-www-form-urlencoded;charset=UTF-8");
            postmethod.setEntity(formEntiry);
            //执行请求
            HttpResponse reponse = client.execute(postmethod);
            //回去返回实体
            HttpEntity entity = reponse.getEntity();
             returnmsg=EntityUtils.toString(entity,"UTF-8");
             EntityUtils.consume(entity);
             //System.out.println(returnmsg);
     }catch(Exception e) {
         returnmsg="fail";
         String action  = paramMap.get("action");
         models.extinterface.ESBBase.saveESBFailedLog(action,url,paramMap,e,null); 
            e.printStackTrace();
     }finally{
             //关闭连接,释放资源
            client.getConnectionManager().shutdown();
     }
      return returnmsg;
    }
   
    //发送https请求
    private static String sendPostHttps(String url, UrlEncodedFormEntity formEntiry,Map<String, String> paramMap) {
        String returnmsg = null;
        SSLClient httpClient = null;
        try { 
         httpClient = new SSLClient(); 
        httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT,10000);//连接时间

        httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT,10000);//数据传输时间
        //响应内容
            HttpPost httpPost = new HttpPost(url);
            httpPost.setHeader(HTTP.CONTENT_TYPE, "application/x-www-form-urlencoded;charset=UTF-8");
            httpPost.setEntity(formEntiry); 
            HttpResponse response = httpClient.execute(httpPost); //执行POST请求 
            System.out.println(response.getStatusLine());
                HttpEntity entity = response.getEntity();             //获取响应实体 
                
                if (null != entity) { 
                    //responseLength = entity.getContentLength(); 
                    returnmsg = EntityUtils.toString(entity, "UTF-8"); 
                    EntityUtils.consume(entity); //销毁的entity  Consume response content
                }
                //System.out.println(returnmsg);
        }catch (Exception e) { 
            returnmsg="fail";
            String action  = paramMap.get("action");
            models.extinterface.ESBBase.saveESBFailedLog(action,url,paramMap,e,null); 
            e.printStackTrace();
        }finally{ 
            if(null != httpClient) {
                httpClient.getConnectionManager().shutdown(); 
            }
        } 
        
      return returnmsg; 
      
    }
}