博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
httpclient4.2 https post接口linux使用TLSv1.2协议
阅读量:4984 次
发布时间:2019-06-12

本文共 6591 字,大约阅读时间需要 21 分钟。

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
paramMap){ String returnmsg=""; try { //封装参数 List
parameters = new ArrayList
(); 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
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
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

你可能感兴趣的文章
bzoj1009: [HNOI2008]GT考试 ac自动机+矩阵快速幂
查看>>
Colidity-- StoneWall
查看>>
Leetcode 904. Fruit Into Baskets
查看>>
怎样连接REDIS服务端
查看>>
ajax同步,加载loading的bug
查看>>
秒杀多线程第二篇 多线程第一次亲密接触 CreateThread与_beginthreadex本质区别
查看>>
div滚动条
查看>>
iOS越狱程序开发
查看>>
一个监听事件监听多个按钮
查看>>
调用其他类的方法
查看>>
SQlite数据库
查看>>
前端开发要注意的浏览器兼容性问题整理
查看>>
Python服务器开发 -- 网络基础
查看>>
开源项目Html Agility Pack实现快速解析Html
查看>>
一些常用的js,jquerry 样例
查看>>
Oracle PL/SQL 多重选择句
查看>>
dorado中的creationType选择类型
查看>>
C++11 数值类型和字符串的相互转换
查看>>
无锡盈达聚力科技有限公司
查看>>
tyvj1659中中救援队
查看>>