Apache HTTPClient以JSON为参数进行HTTPS POST请求

HttpClient的请求很普遍,但有时我们更多地倾向于基于SSL安全的HTTP请求——HTTPS。接口在交互过程中,由于最初采用的是基于Spring的HttpClient请求方式,所以需要修改替换为HTTPS的请求方式。 参考代码

添加maven依赖配置

  <dependency>
			<groupId>org.apache.httpcomponents</groupId>
			<artifactId>httpclient</artifactId>
			<version>4.2.3</version>
		</dependency>
<dependency>
			<groupId>commons-io</groupId>
			<artifactId>commons-io</artifactId>
			<version>2.4</version>
		</dependency>

Apache HTTPS整理代码

package com.wlyd.fmcgwms.util.api;

import java.io.IOException;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import com.alibaba.fastjson.JSONObject;
import com.wlyd.fmcgwms.util.Log;
import com.wlyd.fmcgwms.util.SAASTokenManager;
import com.wlyd.fmcgwms.util.ehcache.EhcacheUtil;
/**
 * Apache HttpClient JSON参数请求方式
 * 
 * @package com.wlyd.fmcgwms.util.api.APIHttpClient
 * @date   2016年11月11日  下午5:46:01
 * @author pengjunlin
 * @comment   
 * @update
 */
public class APIHttpClient {

	// 接口地址
	private String apiURL = "";
	
	private Log logger = Log.getLogger(getClass());
	
	private HttpClient httpClient = null;
	
	private HttpPost method = null;
	
	private long startTime = 0L;
	
	private long endTime = 0L;
	
	private int status = 0;

	/**
	 * 接口地址
	 * 
	 * @param url
	 */
	public APIHttpClient(String url) {
			this.apiURL = url;
			String platformCode = EhcacheUtil.get("WAAS_PLATFORMCODE").toString();
			String memberCode =  EhcacheUtil.get("WAAS_MEMBERCODE").toString();
			httpClient = new DefaultHttpClient();
			method = new HttpPost(apiURL);
			method.setHeader("Accept", "application/json");
			method.setHeader("Accpet-Encoding", "gzip");
			method.setHeader("Content-Encoding", "UTF-8");
			method.setHeader("Content-Type", "application/json; charset=UTF-8");
			method.setHeader("Token", SAASTokenManager.getToken());
			method.setHeader("PlatformCode", platformCode);
			method.setHeader("MemberCode", memberCode);
			method.setHeader("Sequence", UUID.randomUUID().toString());
			
			//========================设置忽略访问SSL===================
			// 创建TrustManager
			X509TrustManager xtm = new 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[] {};
				}
			};
			
			SSLContext ctx=null;
			try {
				ctx = SSLContext.getInstance("SSL");
			} catch (NoSuchAlgorithmException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
			// 使用TrustManager来初始化该上下文,TrustManager只是被SSL的Socket所使用
			try {
				ctx.init(null, new TrustManager[] { xtm }, null);
			} catch (KeyManagementException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
			SSLSocketFactory sf = new SSLSocketFactory(
					ctx,
					SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
			Scheme sch = new Scheme("https", 443, sf);
			httpClient.getConnectionManager().getSchemeRegistry().register(sch);
	}
	
	/**
	 * 接口地址
	 * 
	 * @param url
	 * @param uuid
	 */
	public APIHttpClient(String url,String uuid) {
			apiURL = url;
			String platformCode = EhcacheUtil.get("WAAS_PLATFORMCODE").toString();
			String memberCode =  EhcacheUtil.get("WAAS_MEMBERCODE").toString();
			httpClient = new DefaultHttpClient();
			method = new HttpPost(apiURL);
			method.setHeader("Accept", "application/json");
			method.setHeader("Accpet-Encoding", "gzip");
			method.setHeader("Content-Encoding", "UTF-8");
			method.setHeader("Content-Type", "application/json; charset=UTF-8");
			method.setHeader("Token", SAASTokenManager.getToken());
			method.setHeader("PlatformCode", platformCode);
			method.setHeader("MemberCode", memberCode);
			method.setHeader("Sequence", uuid);
			
			//========================设置忽略访问SSL===================
			// 创建TrustManager
			X509TrustManager xtm = new 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[] {};
				}
			};
			
			SSLContext ctx=null;
			try {
				ctx = SSLContext.getInstance("SSL");
			} catch (NoSuchAlgorithmException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
			// 使用TrustManager来初始化该上下文,TrustManager只是被SSL的Socket所使用
			try {
				ctx.init(null, new TrustManager[] { xtm }, null);
			} catch (KeyManagementException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
			SSLSocketFactory sf = new SSLSocketFactory(
					ctx,
					SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
			Scheme sch = new Scheme("https", 443, sf);
			httpClient.getConnectionManager().getSchemeRegistry().register(sch);
	}

	/**
	 * 调用 API
	 * 
	 * @param parameters
	 * @return
	 */
	public String post(String parameters) {
		String body = null;
		logger.info("parameters:" + parameters);

		if (method != null & parameters != null
				&& !"".equals(parameters.trim())) {
			JSONObject jsonObject = JSONObject.parseObject(parameters);
			logger.info("json:" + jsonObject.toString());
			try {

				List<NameValuePair> params = new ArrayList<NameValuePair>();
				// 建立一个NameValuePair数组,用于存储欲传送的参数
				params.add(new BasicNameValuePair("data", parameters));
				
				StringEntity entity=new StringEntity(parameters, "UTF-8");
				// 添加参数
				method.setEntity(entity/*new UrlEncodedFormEntity(params, "UTF-8")*/);

				startTime = System.currentTimeMillis();

				// 设置编码
				HttpResponse response = httpClient.execute(method);
				endTime = System.currentTimeMillis();
				int statusCode = response.getStatusLine().getStatusCode();
				logger.info("statusCode:" + statusCode);
				logger.info("调用API 花费时间(单位:毫秒):" + (endTime - startTime));
				if (statusCode != HttpStatus.SC_OK) {
					logger.error("Method failed:" + response.getStatusLine());
					status = 1;
				}

				// Read the response body
				body = EntityUtils.toString(response.getEntity());

			} catch (IOException e) {
				// 发生网络异常
				logger.error("exception occurred!\n"
						+ ExceptionUtils.getFullStackTrace(e));
				// 网络错误
				status = 3;
			} finally {
				logger.info("调用接口状态:" + status);
			}

		}
		return body;
	}

	/**
	 * 0.成功 1.执行方法失败 2.协议错误 3.网络错误
	 * 
	 * @return the status
	 */
	public int getStatus() {
		return status;
	}

	/**
	 * @param status
	 *            the status to set
	 */
	public void setStatus(int status) {
		this.status = status;
	}

	/**
	 * @return the startTime
	 */
	public long getStartTime() {
		return startTime;
	}

	/**
	 * @return the endTime
	 */
	public long getEndTime() {
		return endTime;
	}

}

简单重构之后

package com.wlyd.fmcgwms.util.api;

import java.io.IOException;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import com.alibaba.fastjson.JSONObject;
import com.wlyd.fmcgwms.util.Log;
import com.wlyd.fmcgwms.util.SAASTokenManager;
import com.wlyd.fmcgwms.util.ehcache.EhcacheUtil;
/**
 * Apache HttpClient JSON参数请求方式
 * 
 * @package com.wlyd.fmcgwms.util.api.APIHttpClient
 * @date   2016年11月11日  下午5:46:01
 * @author pengjunlin
 * @comment   
 * @update
 */
public class APIHttpClient {

	// 接口地址
	private String apiURL = "";
	
	private Log logger = Log.getLogger(getClass());
	
	private HttpClient httpClient = null;
	
	private HttpPost method = null;
	
	private long startTime = 0L;
	
	private long endTime = 0L;
	
	private int status = 0;
	
	/**
	 * 设置忽略安全验证
	 * 
	 * @MethodName: initHttps 
	 * @Description: 
	 * @throws
	 */
	private void initHttps(){
		//========================设置忽略访问SSL===================
		// 创建TrustManager
		X509TrustManager xtm = new 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[] {};
			}
		};
		
		SSLContext ctx=null;
		try {
			ctx = SSLContext.getInstance("SSL");
		} catch (NoSuchAlgorithmException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		// 使用TrustManager来初始化该上下文,TrustManager只是被SSL的Socket所使用
		try {
			ctx.init(null, new TrustManager[] { xtm }, null);
		} catch (KeyManagementException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		SSLSocketFactory sf = new SSLSocketFactory(
				ctx,
				SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
		Scheme sch = new Scheme("https", 443, sf);
		httpClient.getConnectionManager().getSchemeRegistry().register(sch);
	}

	/**
	 * 接口地址
	 * 
	 * @param url
	 */
	public APIHttpClient(String url) {
			this.apiURL = url;
			String platformCode = EhcacheUtil.get("WAAS_PLATFORMCODE").toString();
			String memberCode =  EhcacheUtil.get("WAAS_MEMBERCODE").toString();
			httpClient = new DefaultHttpClient();
			method = new HttpPost(apiURL);
			method.setHeader("Accept", "application/json");
			method.setHeader("Accpet-Encoding", "gzip");
			method.setHeader("Content-Encoding", "UTF-8");
			method.setHeader("Content-Type", "application/json; charset=UTF-8");
			method.setHeader("Token", SAASTokenManager.getToken());
			method.setHeader("PlatformCode", platformCode);
			method.setHeader("MemberCode", memberCode);
			method.setHeader("Sequence", UUID.randomUUID().toString());
			// 设置忽略访问SSL
			initHttps();
	}
	
	/**
	 * 接口地址
	 * 
	 * @param url
	 * @param uuid
	 */
	public APIHttpClient(String url,String uuid) {
			apiURL = url;
			String platformCode = EhcacheUtil.get("WAAS_PLATFORMCODE").toString();
			String memberCode =  EhcacheUtil.get("WAAS_MEMBERCODE").toString();
			httpClient = new DefaultHttpClient();
			method = new HttpPost(apiURL);
			method.setHeader("Accept", "application/json");
			method.setHeader("Accpet-Encoding", "gzip");
			method.setHeader("Content-Encoding", "UTF-8");
			method.setHeader("Content-Type", "application/json; charset=UTF-8");
			method.setHeader("Token", SAASTokenManager.getToken());
			method.setHeader("PlatformCode", platformCode);
			method.setHeader("MemberCode", memberCode);
			method.setHeader("Sequence", uuid);
			// 设置忽略访问SSL
			initHttps();
	}

	/**
	 * 调用 API
	 * 
	 * @param parameters
	 * @return
	 */
	public String post(String parameters) {
		String body = null;
		logger.info("parameters:" + parameters);

		if (method != null & parameters != null
				&& !"".equals(parameters.trim())) {
			JSONObject jsonObject = JSONObject.parseObject(parameters);
			logger.info("json:" + jsonObject.toString());
			try {

				List<NameValuePair> params = new ArrayList<NameValuePair>();
				// 建立一个NameValuePair数组,用于存储欲传送的参数
				params.add(new BasicNameValuePair("data", parameters));
				
				StringEntity entity=new StringEntity(parameters, "UTF-8");
				// 添加参数
				method.setEntity(entity/*new UrlEncodedFormEntity(params, "UTF-8")*/);

				startTime = System.currentTimeMillis();

				// 设置编码
				HttpResponse response = httpClient.execute(method);
				endTime = System.currentTimeMillis();
				int statusCode = response.getStatusLine().getStatusCode();
				logger.info("statusCode:" + statusCode);
				logger.info("调用API 花费时间(单位:毫秒):" + (endTime - startTime));
				if (statusCode != HttpStatus.SC_OK) {
					logger.error("Method failed:" + response.getStatusLine());
					status = 1;
				}

				// Read the response body
				body = EntityUtils.toString(response.getEntity());

			} catch (IOException e) {
				// 发生网络异常
				logger.error("exception occurred!\n"
						+ ExceptionUtils.getFullStackTrace(e));
				// 网络错误
				status = 3;
			} finally {
				logger.info("调用接口状态:" + status);
			}

		}
		return body;
	}

	/**
	 * 0.成功 1.执行方法失败 2.协议错误 3.网络错误
	 * 
	 * @return the status
	 */
	public int getStatus() {
		return status;
	}

	/**
	 * @param status
	 *            the status to set
	 */
	public void setStatus(int status) {
		this.status = status;
	}

	/**
	 * @return the startTime
	 */
	public long getStartTime() {
		return startTime;
	}

	/**
	 * @return the endTime
	 */
	public long getEndTime() {
		return endTime;
	}

}

利用IDE 查看Apache HttpClient API

输入图片说明

编程小技巧

Maven给了我们许多方便,可以找到对应class以查看其源码。在这里有一个值得查看源码的情形是:在不知道API是否支持你所需要的数据类型时,第一是查看API的官方文档及其源码,第二就是对其源码进行改造以适应当前所需。

资源下载

Github地址

转载于:https://my.oschina.net/boonya/blog/787344

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值