使用commons httpclient请求https协议的webservice
使commons httpclient支持https协议类,是commons httpclient
import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;
import java.net.UnknownHostException;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import javax.net.SocketFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import org.apache.commons.httpclient.ConnectTimeoutException;
import org.apache.commons.httpclient.params.HttpConnectionParams;
import org.apache.commons.httpclient.protocol.ProtocolSocketFactory; /** * httpclient https * */
public class HTTPSSecureProtocolSocketFactory implements ProtocolSocketFactory {//SecureProtocolSocketFactory private SSLContext sslcontext = null;private SSLContext createSSLContext(){SSLContext sslcontext = null;try{sslcontext = SSLContext.getInstance("SSL");sslcontext.init(null, new TrustManager[]{ new TrustAnyTrustManager() }, new java.security.SecureRandom());}catch (NoSuchAlgorithmException e){e.printStackTrace();}catch (KeyManagementException e){e.printStackTrace();}return sslcontext;}private SSLContext getSSLContext(){if (this.sslcontext == null){this.sslcontext = createSSLContext();}return this.sslcontext;}public Socket createSocket(Socket socket, String host, int port,boolean autoClose) throws IOException, UnknownHostException{return getSSLContext().getSocketFactory().createSocket(socket, host,port, autoClose);}public Socket createSocket(String host, int port) throws IOException,UnknownHostException{return getSSLContext().getSocketFactory().createSocket(host, port);}public Socket createSocket(String host, int port, InetAddress clientHost,int clientPort) throws IOException, UnknownHostException{return getSSLContext().getSocketFactory().createSocket(host, port,clientHost, clientPort);}public Socket createSocket(String host, int port, InetAddress localAddress,int localPort, HttpConnectionParams params) throws IOException,UnknownHostException, ConnectTimeoutException{if (params == null){throw new IllegalArgumentException("Parameters may not be null");}int timeout = params.getConnectionTimeout();SocketFactory socketfactory = getSSLContext().getSocketFactory();if (timeout == 0){return socketfactory.createSocket(host, port, localAddress,localPort);}else{Socket socket = socketfactory.createSocket();SocketAddress localaddr = new InetSocketAddress(localAddress,localPort);SocketAddress remoteaddr = new InetSocketAddress(host, port);socket.bind(localaddr);socket.connect(remoteaddr, timeout);return socket;}}// 自定义私有类private static class TrustAnyTrustManager implements X509TrustManager{public void checkClientTrusted(X509Certificate[] chain, String authType)throws CertificateException{}public void checkServerTrusted(X509Certificate[] chain, String authType)throws CertificateException{}public X509Certificate[] getAcceptedIssuers(){return new X509Certificate[]{};}}}
httpclient请求类
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.UsernamePasswordCredentials;
import org.apache.commons.httpclient.auth.AuthScope;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import org.apache.commons.httpclient.protocol.Protocol;public class SoapUtil {/** * <p>Description: 根据请求报文,请求服务地址获取 响应报文 * @param requestSoap 请求报文 * @param serviceAddress 请求地址 * @param charSet 字符集 utf-8* @param contentType 类型 text/xml; charset=utf-8* @return map封装的 服务器响应参数和返回报文.PS:statusCode :200正常响应。responseSoap:响应报文 * <p>thinking: </p> * * @author */public static Map<String,Object> responseSoap(String requestSoap,String serviceAddress,String charSet, String contentType){ String responseSoap=""; Map<String,Object> resultmap=new HashMap<String,Object>(); PostMethod postMethod = new PostMethod(serviceAddress); HttpClient httpClient = new HttpClient(); Protocol myhttps = new Protocol("https", new HTTPSSecureProtocolSocketFactory(), 443);//支持httpsProtocol.registerProtocol("https", myhttps);int statusCode = 0; try { httpClient.getState().setCredentials(AuthScope.ANY, new UsernamePasswordCredentials("USERNAME", "PASSWORD"));//设置用户名密码,如果不需要就忽略这一行StringRequestEntity entity = new StringRequestEntity(requestSoap,contentType,charSet);postMethod.setRequestEntity(entity); statusCode = httpClient.executeMethod(postMethod); resultmap.put("statusCode", statusCode); } catch (IOException e) { throw new RuntimeException("执行http请求失败", e); } if (statusCode == 200) { try { responseSoap = postMethod.getResponseBodyAsString(); resultmap.put("responseSoap", responseSoap); } catch (IOException e) { throw new RuntimeException("获取请求返回报文失败", e); } } else { throw new RuntimeException("请求失败:" + statusCode); } return resultmap; } }
xml工具类
import java.io.IOException;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
import org.xml.sax.InputSource;public class XmlUtil {/** * <p>Description:将字符串类型的XML 转化成Docunent文档结构</p> * @param parseStrXml 待转换的xml 字符串 * @return Document * * @author * @throws JDOMException * @throws IOException */ public static Document strXmlToDocument(String parseStrXml) throws JDOMException, IOException{ StringReader read = new StringReader(parseStrXml); //创建新的输入源SAX 解析器将使用 InputSource 对象来确定如何读取 XML 输入 InputSource source = new InputSource(read); //创建一个新的SAXBuilder SAXBuilder sb = new SAXBuilder(); // 新建立构造器 Document doc = null; try { doc = sb.build(source); } catch (JDOMException e) {throw e;} catch (IOException e) { throw e; } return doc; } /** * <p>Description: 根据目标节点名获取值</p> * @param doc 文档结构 * @param finalNodeName 最终节点名 * @return * * @author */ public static String getValueByElementName(Document doc,String finalNodeName){ Element root = doc.getRootElement(); HashMap<String,Object> map=new HashMap<String,Object>(); //调用getChildAllText方法。获取目标子节点的值 getChildAllText(doc, root,map); String result=(String)map.get(finalNodeName); return result; } /** * <p>Description: 递归获得子节点的值</p> * @param doc 文档结构 * @param e 节点元素 * @param resultmap 递归将值压入map中 * @return * * @author */ public static Map<String, Object> getChildAllText(Document doc, Element e,Map<String, Object> resultmap) {if (e != null) {if (e.getChildren() != null) // 如果存在子节点{List<Element> list = e.getChildren();for (Element el : list) // 循环输出{if (el.getChildren().size() > 0) // 如果子节点还存在子节点,则递归获取{getChildAllText(doc, el, resultmap);} else {resultmap.put(el.getName(), el.getTextTrim()); // 将叶子节点值压入map}}}}return resultmap;}/*** 获取某个节点下的所有子节点* @param doc* @param element* @return*/public static List<Element> getChildToList(Document doc,String element){Element root = doc.getRootElement();Element e = root.getChild(element);if(e != null){ //判断要查找的节点是否存在根节点,return e.getChildren();//存在:返回节点下的所有子节点}else{return getChildToList(root, element);//不存在:进入递归查询}}/*** 递归查找节点* @param root* @param element* @return*/private static List<Element> getChildToList(Element root,String element){List<Element> list = new ArrayList<>();List<Element> rootElements = root.getChildren();for (Element element2 : rootElements) {if(element2.getChild(element)!=null){return element2.getChild(element).getChildren();}else{list = getChildToList(element2, element);if(list.size() != 0)return list;}}return new ArrayList<>();}
}
使用commons httpclient请求https协议的webservice相关推荐
- org.apache.commons.httpclient 访问需要验证的webservice的一些问题
1.httpclient验证问题 webservice需要验证时,直接发送请求会返回 HTTP/1.1 401 Unauthorized 错误 这时候需要设置: Credentials default ...
- HttpWebRequest 请求HTTPS协议时报错:The requested security protocol is not supported. (不支持请求的安全协议)
public String Get(string url, byte[] data){HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Creat ...
- http协议请求https协议报错或警告处理方案
HTTPS是HTTP over Secure Socket Layer,以安全为目标的 HTTP 通道,所以在 HTTPS 承载的页面上不允许出现 http 请求,一旦出现就是提示或报错: 如果我们不 ...
- 接口测试自动化之坑二:如何使用requests库请求https协议,解决提示报错和Unverified HTTPS request警告warning问题
1.首先在请求的requests中增加一条verify=False设置次参数的目的是跳过SSL证书问题 2.设置步骤一后,控制台会有Unverified HTTPS request报错信息 解决办法: ...
- QQ总显示服务器请求中,网站添加QQ登陆 报错 可能是服务器无法请求https协议 解决方法...
最近一个项目要整合qq互联登陆,在使用sdk的时候就发现了这个问题:可能未开启curl支持,请尝试开启curl支持,重启web服务器,如果问题仍未解决,请联系我们 实在太尴尬了,网上找了些方法!感觉没 ...
- httpf发送 json_Java用HttpClient3发送http/https协议get/post请求,发送map,json,xml,txt数据...
使用的是httpclient 3.1, 使用"httpclient"4的写法相对简单点,百度:httpclient https post 当不需要使用任何证书访问https网页时, ...
- httpf发送 json_Java用HttpClient4发送http/https协议get/post请求,发送map,json,xml,txt数据...
刚写出来的,还未经测试, HttpUtil.java import java.io.IOException; import java.io.UnsupportedEncodingException; ...
- Android 使用自带的HttpClient进行https请求出现403的解决过程记录
2019独角兽企业重金招聘Python工程师标准>>> 出现的过程 最近在用程序模拟一个web站的https登录,然后进行一些后续操作的小玩意.先使用java程序写测试代码,测试通过 ...
- iOS ASIHTTPRequest用https协议加密请求
iOS 终端请求服务端数据时,为了保证数据安全,我们一般会使用https协议加密,而对于iOS的网络编程,我们一般会使用开源框架:ASIHTTPRequest,但是如果使用传统的http方式,即使忽略 ...
最新文章
- mysql锁总结知乎_Mysql悲观锁乐观锁区别与使用场景
- github如何clone别人commit的历史版本的仓库
- 【转】根据起止日期+时间取数
- 起点linux和深度linux哪个好,我想深入学习linux计算机,但不知道选择哪个版本好?...
- 【Flink】SqlValidatorException: Column xxx not found in any table
- Android之实现 A/B分区更新固件
- SQL Server 中位数、标准差、平均数
- oracle毕业论文题目,2012届本科毕业论文设计题目参考
- M32S 串口摄像头的技术应用
- 六级,我一定要考好!
- 【案例7】NC+ORACLE+系统初始化的完整操作顺序
- 如何编写没有工作经验的简历
- C++图书管理系统_艾孜尔江撰
- 银行卡资费转帐汇款取款_收费标准参考_中行_建行_工行_农行_招行_兴业等
- 未来智安2周年 | 行则将至,未来可期
- mysql常见函数面试题_MySql三到常见面试题,整理总结一下
- 网管日记:故障网络交换机快速替换方法
- LLVM学习日志2——PASS尝试
- 如何用电脑收发传真?电脑怎么收传真?电脑怎么发传真?
- /prod-api/ 整合阿里云服务器 2020年12月13日 23:44:18(日记)