HttpClientUtils获取responseCode(含https)

使用apache的httpclient支持SSL(https)安全协议

1.调用方法

int code = HttpClientUtils.postForReturnCode(url.toString());

 2.HttpClientUtils代码

package com.sf.integration.sso.access;

import java.net.URL;
import java.security.Security;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.protocol.Protocol;
import org.apache.commons.httpclient.protocol.ProtocolSocketFactory;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

public class HttpClientUtils {
	
	private static final Logger log = Logger.getLogger(HttpClientUtils.class);

	public static String get(String url) {
		return send("get", url);
	}

	public static String post(String url) {
		return send("post", url);
	}
	
	//返回code的方法
	public static int postForReturnCode(String url) {
		return sendForReturnCode("post", url);
	}
	
	public static String send(String method, String url) {
		String body = "error";
		HttpMethod httpMethod = null;
		if (method.equalsIgnoreCase("post")) {
			httpMethod = new PostMethod(url); // 输入网址
		} else {
			httpMethod = new GetMethod(url); // 输入网址
		}
		HttpClient client = new HttpClient();
		try {
			if (url.startsWith("https:")) {
				supportSSL(url, client);
			}
			client.getParams().setContentCharset("UTF-8"); // 处理中午字符串
			client.executeMethod(httpMethod);
			body = httpMethod.getResponseBodyAsString();
			int code = httpMethod.getStatusCode();
			System.out.println(code);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return body;
	}
	
	public static int sendForReturnCode(String method, String url) {
		int code = 403;
		HttpMethod httpMethod = null;
		if (method.equalsIgnoreCase("post")) {
			httpMethod = new PostMethod(url); // 输入网址
		} else {
			httpMethod = new GetMethod(url); // 输入网址
		}
		HttpClient client = new HttpClient();
		try {
			if (url.startsWith("https:")) {
				supportSSL(url, client);
			}
			client.getParams().setContentCharset("UTF-8"); // 处理中午字符串
			client.executeMethod(httpMethod);
			code = httpMethod.getStatusCode();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return code;
	}
	
	private static void supportSSL(String url, HttpClient client) {
        if(StringUtils.isBlank(url)) {
            return;
        }
        String siteUrl = StringUtils.lowerCase(url);
        if (!(siteUrl.startsWith("https"))) {
            return;
        }
       
        try {
           setSSLProtocol(siteUrl, client);
        } catch (Exception e) {
            log.error("setProtocol error ", e);
        }
        Security.setProperty( "ssl.SocketFactory.provider","com.tool.util.DummySSLSocketFactory");
    }
	
	private static void setSSLProtocol(String strUrl, HttpClient client) throws Exception {	       
        URL url = new URL(strUrl);
        String host = url.getHost();
        int port = url.getPort();

        if (port <= 0) {
            port = 443;
        }
        ProtocolSocketFactory factory = new DummySSLSocketFactory();
        Protocol authhttps = new Protocol("https", factory, port);
        Protocol.registerProtocol("https", authhttps);
        client.getHostConfiguration().setHost(host, port, authhttps);
    }
}

 3.DummySSLSocketFactory验证代码

package com.sf.integration.sso.access;

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.SecureProtocolSocketFactory;


public class DummySSLSocketFactory implements 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[]{};
        }
    }

}

 

你可能感兴趣的:(java基础)