HttpClient使用demo

58 篇文章 0 订阅
package com.lxy;

import java.util.HashMap;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;

public class MyHttpClient {

	private static Logger logger = Logger.getLogger(MyHttpClient.class);

	public static HashMap doPost(String url, HashMap para, long waitTime) throws Exception {
		if (url == null || "".equals(url)) {
			throw new Exception("服务地址为空,请检查");
		}

		// 创建请求
		HttpPost httppost = new HttpPost(url);

		// 附加请求头
		httppost.setHeader("Content-Type", "application/json");
		httppost.setHeader("accept", "application/json");

		// 请求体
		setHttpBody(httppost, para);

		// 连接配置
		setHttpConfig(httppost, waitTime);

		// 执行
		String result = doExecute(httppost);

		// 解析json出参为Map
		return parseJsonToMap(result);
	}

	/**
	 * 执行http请求,返回值
	 * @param httppost
	 * @return
	 * @throws Exception
	 */
	private static String doExecute(HttpPost httppost) throws Exception {
		CloseableHttpClient httpclient = null;
		CloseableHttpResponse response = null;
		HttpEntity entity = null;

		try {
			// 创建客户端
			httpclient = HttpClients.createDefault();

			// 执行
			response = httpclient.execute(httppost);

			// 判断返回码
			checkResponseStatus(response);

			// 获取response中的报文体
			entity = response.getEntity();

			String result = "";
			if (entity != null) {
				result = EntityUtils.toString(entity, "UTF-8");
			}

			return result;
		} finally {
			try {
				if (entity != null) {
					EntityUtils.consume(entity);
				}
			} catch (Exception e2) {
				logger.error("invokeService释放entity连接时出现异常。", e2);
			}

			try {
				if (response != null) {
					response.close();
				}
			} catch (Exception e2) {
				logger.error("释放response连接时出现异常。", e2);
			}

			try {
				if (httppost != null) {
					httppost.releaseConnection();
				}
			} catch (Exception e2) {
				logger.error("invokeService释放httppost连接时出现异常。", e2);
			}

			try {
				if (httpclient != null) {
					httpclient.close();
				}
			} catch (Exception e2) {
				logger.error("释放httpclient连接时出现异常。", e2);
			}
		}
	}

	/**
	 * response状态校验
	 * @param response
	 * @throws Exception
	 */
	private static void checkResponseStatus(HttpResponse response) throws Exception {
		int statusCode = response.getStatusLine().getStatusCode();

		if (statusCode != 200) {
			throw new Exception(" http返回码为" + statusCode);
		}
	}

	private static void setHttpConfig(HttpPost httppost, long waitTime) {
		RequestConfig rconfig = RequestConfig.custom().setConnectTimeout((int) waitTime)
				.setSocketTimeout((int) waitTime).build();
		httppost.setConfig(rconfig);
	}

	/**
	 * map参数转json
	 * @param httppost
	 * @param para
	 * @throws Exception
	 */
	private static void setHttpBody(HttpPost httppost, HashMap para) throws Exception {
		ObjectMapper objMapper = new ObjectMapper();
		String json = objMapper.writeValueAsString(para);
		
		StringEntity jsonStringEntity = new StringEntity(json, "UTF-8");
		
		httppost.setEntity(jsonStringEntity);
	}
	
	/**
	 * json串转map  jackson
	 * @param result
	 * @return
	 * @throws JsonMappingException
	 * @throws JsonProcessingException
	 */
	private static HashMap parseJsonToMap(String result) throws JsonMappingException, JsonProcessingException {
		ObjectMapper objMapper = new ObjectMapper();
		
		HashMap readValue = objMapper.readValue(result, HashMap.class);
		return readValue;
	}
}

 

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值