资讯专栏INFORMATION COLUMN

使用commons httpclient请求https协议的webservice

VPointer / 2032人阅读

摘要:使支持协议类,是自定义私有类请求类根据请求报文,请求服务地址获取响应报文请求报文请求地址字符集类型封装的服务器响应参数和返回报文正常响应。

使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 {

    /**  
        * 

Description: 根据请求报文,请求服务地址获取 响应报文 * @param requestSoap 请求报文 * @param serviceAddress 请求地址 * @param charSet 字符集 utf-8 * @param contentType 类型 text/xml; charset=utf-8 * @return map封装的 服务器响应参数和返回报文.PS:statusCode :200正常响应。responseSoap:响应报文 *

thinking:

* * @author */ public static Map responseSoap(String requestSoap,String serviceAddress,String charSet, String contentType){ String responseSoap=""; Map resultmap=new HashMap(); PostMethod postMethod = new PostMethod(serviceAddress); HttpClient httpClient = new HttpClient(); Protocol myhttps = new Protocol("https", new HTTPSSecureProtocolSocketFactory(), 443);//支持https Protocol.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 {

    
    
    
     /** 
     * 

Description:将字符串类型的XML 转化成Docunent文档结构

* @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; } /** *

Description: 根据目标节点名获取值

* @param doc 文档结构 * @param finalNodeName 最终节点名 * @return * * @author */ public static String getValueByElementName(Document doc,String finalNodeName){ Element root = doc.getRootElement(); HashMap map=new HashMap(); //调用getChildAllText方法。获取目标子节点的值 getChildAllText(doc, root,map); String result=(String)map.get(finalNodeName); return result; } /** *

Description: 递归获得子节点的值

* @param doc 文档结构 * @param e 节点元素 * @param resultmap 递归将值压入map中 * @return * * @author */ public static Map getChildAllText(Document doc, Element e,Map resultmap) { if (e != null) { if (e.getChildren() != null) // 如果存在子节点 { List 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 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 getChildToList(Element root,String element){ List list = new ArrayList<>(); List 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<>(); } }

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/67942.html

相关文章

  • 构建https协议webService使用httpClient接口访问

    摘要:组件版本信息使用自带的命令生成文件命令将拷贝到目录下配置的目录文件,在配置文件中新增配置将工程添加进并启动,使用访问和链接。原理后续进一步研究 1.组件版本信息apache-tomcat-7.0.75JDK 1.8.0_91 2.使用jdk自带的keytool命令生成keystore文件test.keystore命令:keytool -genkey -alias test123 -ke...

    Tony_Zby 评论0 收藏0
  • WebService就是这么简单

    摘要:它使用方式,接收和响应外部系统的某种请求。回顾我们在学习基础网络编程章节已经知道了这么一个连接了。使用指定名称的命名空间。名词简单对象访问协议作为一个基于语言的协议用于有网上传输数据。以的根元素出现。代理这么一个概念就更加清晰了。 WebService介绍 首先我们来谈一下为什么需要学习webService这样的一个技术吧.... 问题一 如果我们的网站需要提供一个天气预报这样一个需求...

    SwordFly 评论0 收藏0
  • 互亿无线短信发送

    摘要:最近几天有机会到了一家科技公司,和里面的项目经理聊了一下后端技术,他对我的讲了一下需要会的一些基本技术,其中提到了验证短信发送,今天我就刚学习了验证短信发送信息,主要运用互亿无线短信平台进行发送直入主题。 最近几天有机会到了一家科技公司,和里面的项目经理聊了一下后端技术,他对我的讲了一下需要会的一些基本技术,其中提到了验证短信发送,今天我就刚学习了验证短信发送信息,主要运用互亿无线短信...

    DobbyKim 评论0 收藏0

发表评论

0条评论

最新活动
阅读需要支付1元查看
<