java httpclient post application/json

  • Post author:
  • Post category:java


package com.awj.mall.lm.util;


import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.StatusLine;
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 com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.awj.mall.config.properties.AdminLmProperties;
import com.awj.mall.core.util.SpringContextHolder;
/**
 * 
 * @author ljj
 * 绿米接口请求工具类
 *
 */
public class LmHttpClientUtil {

	private static AdminLmProperties apiLmProperties = SpringContextHolder.getBean(AdminLmProperties.class);

	private static Log log = LogFactory.getLog(LmHttpClientUtil.class);

	public static JSONObject doPost(Map<String, Object> params, String urlHz) {
		// 组装请求参数
		long t = System.currentTimeMillis();
		String appId = apiLmProperties.getAppId();
		String appKey = apiLmProperties.getAppKey();
		String url = apiLmProperties.getUrl() + urlHz;
		//System.out.print("*************************************url:"+url);
		//String appId = "A39NmUvB";
		//String appKey = "b19109fa47fc4efc9c1da83a0b7abf21";
		//String url = "https://saas-test.aqara.cn/open/api/retail" + urlHz;
		// Map<String, Object> params = new HashMap<>();
		// params.put("type", "SERVICE");
		// params.put("status", "N");
		// 拼接加密原串 (固定顺序)
		String data = JSON.toJSONString(params);
		StringBuilder str = new StringBuilder();
		str.append("appId=").append(appId).append("&");
		str.append("timestamp=").append(t).append("&");
		str.append("data=").append(data).append("&");
		str.append("appKey=").append(appKey);
		String sign = DigestUtils.sha256Hex(str.toString());

		// 组装请求参数
		Map<String, Object> body = new HashMap<>();
		body.put("appId", appId);
		body.put("timestamp", t);
		body.put("sign", sign);
		body.put("data", data);

		// 发起请求
		String resp = null;
		try {
			resp = doPost(url, JSON.toJSONString(body));
			log.info("拉取信息:{}" + resp);
		} catch (Exception e) {
			log.error("调用绿米接口失败", e);
		}
		if (resp == null) {
			return null;
		}
		return JSON.parseObject(resp);
	}

	/**
	 * post请求(用于请求json格式的参数)
	 * 
	 * @param url
	 * @param params
	 * @return
	 */
	private static String doPost(String url, String params) throws Exception {

		CloseableHttpClient httpclient = HttpClients.createDefault();
		HttpPost httpPost = new HttpPost(url);// 创建httpPost
		httpPost.setHeader("Accept", "application/json");
		httpPost.setHeader("Content-Type", "application/json");
		String charSet = "UTF-8";
		StringEntity entity = new StringEntity(params, charSet);
		httpPost.setEntity(entity);
		CloseableHttpResponse response = null;

		try {

			response = httpclient.execute(httpPost);
			StatusLine status = response.getStatusLine();
			int state = status.getStatusCode();
			if (state == HttpStatus.SC_OK) {
				HttpEntity responseEntity = response.getEntity();
				String jsonString = EntityUtils.toString(responseEntity);
				return jsonString;
			} else {
				log.error("请求返回:" + state + "(" + url + ")");
			}
		} finally {
			if (response != null) {
				try {
					response.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			try {
				httpclient.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return null;
	}

}



版权声明:本文为weixin_39522272原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。