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

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

 

转载于:https://www.cnblogs.com/woftlcj/p/8426422.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值