使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);//支持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 {

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

AnDe
67 声望3 粉丝

???:“他会经常忘记代码的语法和一些API,所以他经常需要去查API甚至查语法,他觉得没有Google我几乎没法工作。这在某些人的眼里,是技术不够的表现。他记的只是一个Key,一个如何找寻答案的索引,而不是全部,人...


下一篇 »
LAMP安装