文档章节

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

boonya
 boonya
发布于 2016/11/14 11:52
字数 1516
阅读 861
收藏 2

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地址

© 著作权归作者所有

boonya
粉丝 76
博文 308
码字总数 61673
作品 0
海淀
高级程序员
私信 提问
Android 浅谈HttpClient工具类

在Android开发中我们经常会用到网络连接功能与服务器进行数据的交互,为此Android的SDK提供了Apache的HttpClient来方便我们使用各种Http服务。你可以把HttpClient想象成一个浏览器,通过它的...

Jonson
2013/07/25
714
3
Apache HttpClient 资源释放、请求超时,导致线程池用光、内存不足

Apache HttpClient,据说很强大,可以支持峰值一秒7万以上的请求。不过需要注意一些资源释放和超时处理的问题。 问题1:线程资源无法释放,最终导致内存不足、或线程池被用光。 问题代码: ...

onedotdot
2018/10/17
347
0
Android开发_网络编程之Http通信

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/zhangty0223/article/details/9410261 Android中提供的HttpURLConnection和HttpClient接口可以用来开发HTTP程...

张腾元_Ternence
2013/07/22
0
0
原生POST请求比apache httpClient快

发现用JDK原生的POST请求比Apache的请求要快。记录一下 原生的代码 public static JSONObject sendPost(String postUrl, String strReqJsonStr) throws Exception { JSONObject respJson = n......

奋斗的小牛
2018/08/28
129
0
apache.commons.httpclient.HttpClient get/post请求

一、httpclient 发送请求的步骤(流程) 1、创建httpclient 对象 2、创建某种连接方式的对象 --如 GetMethod PostMethod 等对象,构造函数中是请求地址即url,如果是get请求可以在url后面添加...

QH_C
2015/04/13
170
0

没有更多内容

加载失败,请刷新页面

加载更多

redis 内存信息解析

used_memory:由 Redis 分配器分配的内存总量,包含了redis进程内部的开销和数据占用的内存,以字节(byte)为单位 used_memory_rss:向操作系统申请的内存大小。与 top 、 ps等命令的输出一...

Canaan_
23分钟前
2
0
windows 下 python3 安装 pip setuptools

本文链接:https://blog.csdn.net/huzuxing/article/details/80807744 最近在家使用python的时候,总是报setuptools 模块未找到,于是在网上搜索了相关解决办法,但是都没有解决问题。 于是去...

开源中国首席CYO
29分钟前
3
0
数据库添加索引

mysql索引添加 navicat 步骤 - 选择表 -> 设计表 ->索引

以谁为师
39分钟前
5
0
java7与java9中的try-finally关闭资源

1.java7中的try 在java7之前,对于一些需要使用finally关闭资源的操作,会显得很臃肿. try{//}catch(Exception e){//}finally{if(xxxx != null){xxxx.close();}} 在jav...

Blueeeeeee
41分钟前
3
0
字节序转换详解

在跨平台和网络编程中我们经常会提到网络字节序和主机字节序,如果没有正确对两者进行转换,从而导致两方产生了不同的解释,就会出现意想不到的bug。 目录 0x01 概念 0x02 分类 0x03 两种字节...

无心的梦呓
51分钟前
4
0

没有更多内容

加载失败,请刷新页面

加载更多

返回顶部
顶部