org.apache.commons.httpclient.HttpClient的https使用方法介绍

Home / Android MrLee 2015-6-15 11604

本例子是commons-httpclient.jar包里面的org.apache.commons.httpclient.HttpClient,请不要搞混淆了。
package com.vdemo;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.RequestEntity;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import org.apache.commons.httpclient.protocol.Protocol;
import org.apache.commons.httpclient.protocol.ProtocolSocketFactory;
import org.apache.commons.io.IOUtils;
import com.alibaba.fastjson.JSON;
public class PublicController {
	
	/** 测试用(开发者需换成自己的appkey和secret) */
	static String key = "";
	static String secret = "";
	protected static Map paramsInit(String method,
			Map paramsMap) {
		Map map = new HashMap();
		long time = System.currentTimeMillis() / 1000;
		StringBuilder paramString = new StringBuilder();
		List paramList = new ArrayList();
		for (Iterator it = paramsMap.keySet().iterator(); it.hasNext();) {
			String key1 = it.next();
			String param = key1 + ":" + paramsMap.get(key1);
			paramList.add(param);
		}
		String[] params = paramList.toArray(new String[paramList.size()]);
		Arrays.sort(params);
		for (String param : params) {
			paramString.append(param).append(",");
		}
		paramString.append("method").append(":").append(method).append(",");
		paramString.append("time").append(":").append(time).append(",");
		paramString.append("secret").append(":").append(secret);
		// System.out.println(paramString.toString().trim());
		String sign = DigestUtils.md5Hex(paramString.toString().trim());
		Map systemMap = new HashMap();
		systemMap.put("ver", "1.0");
		systemMap.put("sign", sign);
		systemMap.put("key", key);
		systemMap.put("time", time);
		map.put("system", systemMap);
		map.put("method", method);
		map.put("params", paramsMap);
		map.put("id", "123456");
		return map;
	}
	protected static String doPost(Map map) {
		String json = JSON.toJSONString(map);
		ProtocolSocketFactory fcty = new MySecureProtocolSocketFactory();
		Protocol.registerProtocol("https", new Protocol("https", fcty, 443));
		HttpClient client = new HttpClient();
		// 使用POST方法
		PostMethod method = new PostMethod(
				"https://open.ithtw.com:443/api/method");
		try {
			RequestEntity entity = new StringRequestEntity(json,
					"application/json", "UTF-8");
			method.setRequestEntity(entity);
			client.executeMethod(method);
			InputStream inputStream = method.getResponseBodyAsStream();
			String restult = IOUtils.toString(inputStream);
			return restult;
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			// 释放连接
			method.releaseConnection();
		}
		return null;
	}
}
用到了几个jar包,一个是commons-httpclient.jar要去掉.rar结尾才可以用,另外一个是commons-codec.jar同样要去掉.rar结尾。fastjson-1.1.6.jar
package com.vdemo;

import java.io.IOException;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import org.apache.commons.httpclient.ConnectTimeoutException;
import org.apache.commons.httpclient.HttpClientError;
import org.apache.commons.httpclient.params.HttpConnectionParams;
import org.apache.commons.httpclient.protocol.ControllerThreadSocketFactory;
import org.apache.commons.httpclient.protocol.SecureProtocolSocketFactory;
public class MySecureProtocolSocketFactory implements SecureProtocolSocketFactory {
    private SSLContext sslContext = null;
    /**
     * Constructor for MySecureProtocolSocketFactory.
     */
    public MySecureProtocolSocketFactory() {
    }
    /**
     * @return
     */
    private static SSLContext createEasySSLContext() {
        try {
            SSLContext context = SSLContext.getInstance("SSL");
            context.init(null, new TrustManager[] {new MyX509TrustManager()}, null);
            return context;
        } catch (Exception e) {
            throw new HttpClientError(e.toString());
        }
    }
    /**
     * @return
     */
    private SSLContext getSSLContext() {
        if (this.sslContext == null) {
            this.sslContext = createEasySSLContext();
        }
        return this.sslContext;
    }
    /*
     * (non-Javadoc)
     * @see
     * org.apache.commons.httpclient.protocol.ProtocolSocketFactory#createSocket(java.lang.String,
     * int, java.net.InetAddress, int)
     */
    public Socket createSocket(String host, int port, InetAddress clientHost, int clientPort) throws IOException,
        UnknownHostException {
        return getSSLContext().getSocketFactory().createSocket(host, port, clientHost, clientPort);
    }
    /*
     * (non-Javadoc)
     * @see
     * org.apache.commons.httpclient.protocol.ProtocolSocketFactory#createSocket(java.lang.String,
     * int, java.net.InetAddress, int, org.apache.commons.httpclient.params.HttpConnectionParams)
     */
    public Socket createSocket(final String host, final int port, final InetAddress localAddress, final int localPort,
            final HttpConnectionParams params) throws IOException, UnknownHostException, ConnectTimeoutException {
        if (params == null) {
            throw new IllegalArgumentException("Parameters may not be null");
        }
        int timeout = params.getConnectionTimeout();
        if (timeout == 0) {
            return createSocket(host, port, localAddress, localPort);
        } else {
            return ControllerThreadSocketFactory.createSocket(this, host, port, localAddress, localPort, timeout);
        }
    }
    /*
     * (non-Javadoc)
     * @see SecureProtocolSocketFactory#createSocket(java.lang.String,int)
     */
    public Socket createSocket(String host, int port) throws IOException, UnknownHostException {
        return getSSLContext().getSocketFactory().createSocket(host, port);
    }
    /*
     * (non-Javadoc)
     * @see SecureProtocolSocketFactory#createSocket(java.net.Socket,java.lang.String,int,boolean)
     */
    public Socket createSocket(Socket socket, String host, int port, boolean autoClose) throws IOException,
        UnknownHostException {
        return getSSLContext().getSocketFactory().createSocket(socket, host, port, autoClose);
    }
}
package com.vdemo;

import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import javax.net.ssl.X509TrustManager;
public class MyX509TrustManager implements X509TrustManager {
    /*
     * (non-Javadoc)
     * @see javax.net.ssl.X509TrustManager#checkClientTrusted(java.security.cert.X509Certificate[],
     * java.lang.String)
     */
    public void checkClientTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
    }
    /*
     * (non-Javadoc)
     * @see javax.net.ssl.X509TrustManager#checkServerTrusted(java.security.cert.X509Certificate[],
     * java.lang.String)
     */
    public void checkServerTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
    }
    /*
     * (non-Javadoc)
     * @see javax.net.ssl.X509TrustManager#getAcceptedIssuers()
     */
    public X509Certificate[] getAcceptedIssuers() {
        return null;
    }
}

本文链接:https://www.it72.com/3465.htm

推荐阅读
最新回复 (0)
返回