linux环境请求HTTPS

linux环境请求HTTPS需求使用SSL连接方式
SSL工具类


package com.xxx.safetycalls;

import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.Principal;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpParams;

/**
 * SSL连接工具类
 */
@SuppressWarnings("deprecation")
public class SslUtils {

	/**
	 * 获取SSL连接
	 * @param ip
	 * @param port
	 * @return
	 */
	public static DefaultHttpClient getHttpClient(String ip, int port) {
		DefaultHttpClient httpClient = null;
		try {
			HttpParams httpParams = new BasicHttpParams();
			httpParams.setParameter("https.protocols", "SSLv3,SSLv2Hello");
			SslUtils chc = new SslUtils();
			httpClient = chc.registerSSL(ip, "TLS", port, "https");
			httpClient.setParams(httpParams);
		} catch (Throwable e) {
			e.printStackTrace();
		}
		return httpClient;
	}

	/**
	 * 注册SSL连接
	 * @param hostname 请求的主机名(IP或者域名)
	 * @param protocol 请求协议名称(TLS-安全传输层协议)
	 * @param port 端口号
	 * @param scheme 协议名称
	 * @return HttpClient实例
	 * @throws NoSuchAlgorithmException
	 * @throws KeyManagementException
	 */
	private DefaultHttpClient registerSSL(String hostname, String protocol, int port, String scheme) throws NoSuchAlgorithmException, KeyManagementException {
		// 创建一个默认的HttpClient
		DefaultHttpClient httpclient = new DefaultHttpClient();
		// 创建SSL上下文实例
		SSLContext ctx = SSLContext.getInstance(protocol);
		// 服务端证书验证
		X509TrustManager tm = new X509TrustManager() {
			/**
			 * 验证客户端证书
			 */
			public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
				// 这里跳过客户端证书 验证
			}

			/**
			 * 验证服务端证书
			 * 
			 * @param chain 证书链
			 * @param authType 使用的密钥交换算法,当使用来自服务器的密钥时authType为RSA
			 */
			public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
				if (chain == null || chain.length == 0)
					throw new IllegalArgumentException("null or zero-length certificate chain");
				if (authType == null || authType.length() == 0)
					throw new IllegalArgumentException("null or zero-length authentication type");

				boolean br = false;
				Principal principal = null;
				for (X509Certificate x509Certificate : chain) {
					principal = x509Certificate.getSubjectX500Principal();
					if (principal != null) {
						br = true;
						return;
					}
				}
				if (!br) {
					throw new CertificateException("服务端证书验证失败!");
				}
			}

			/**
			 * 返回CA发行的证书
			 */
			public X509Certificate[] getAcceptedIssuers() {
				return new X509Certificate[0];
			}
		};

		// 初始化SSL上下文
		ctx.init(null, new TrustManager[] { tm }, new java.security.SecureRandom());
		// 创建SSL连接
		SSLSocketFactory socketFactory = new SSLSocketFactory(ctx, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
		Scheme sch = new Scheme(scheme, port, socketFactory);
		// 注册SSL连接
		httpclient.getConnectionManager().getSchemeRegistry().register(sch);
		return httpclient;
	}

}

请求工具类:


import java.io.ByteArrayInputStream;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.InetAddress;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.Consts;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.BasicHttpEntity;
import org.apache.http.entity.ContentType;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicHeader;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
public class HttpUtils{
	public static String getConnection(String url,String content) {
		String result = null;
		ContentType contentType = null;
		try {
			contentType = ContentType.create("application/json", Consts.UTF_8);
			// 包头
			Header[] headerArray = { 
					new BasicHeader("Accept", "application/json"),
					new BasicHeader("Content-Type", "application/json;charset=UTF-8"),
					new BasicHeader("Host", "api.qingmayun.com")
					};

			InetAddress address = null;
			address = InetAddress.getByName(BASE_REST_URL);
			String ip = address.getHostAddress().toString();
			DefaultHttpClient httpClient = SslUtils.getHttpClient(ip, BASE_REST_PORT);
			//设置连接超时10秒
			httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT,10000);
			httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 10000);
			
			HttpEntity entity = null;

			BasicHttpEntity requestBody = new BasicHttpEntity();
			requestBody.setContent(new ByteArrayInputStream(content.getBytes("utf-8")));
			requestBody.setContentLength(content.getBytes("utf-8").length);
			HttpPost httpPost = new HttpPost(url);
			httpPost.setHeaders(headerArray);
			httpPost.setEntity(requestBody);
			HttpResponse response = httpClient.execute(httpPost);
			entity =response.getEntity();
			
			if (entity != null) {
				result = EntityUtils.toString(entity, "utf-8");
				EntityUtils.consume(entity);
			}
			httpClient.close();
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}
}