http请求规范

名称 规范
传输方式 采用HTTP(S)传输
提交方式 采用POST方法提交
数据格式 请求和响应数据都为JSON格式
字符编码 统一采用UTF-8字符编码
请求头 Content-Type:application/json; charset=utf-8
签名算法 HMAC-MD5
签名要求 请求和响应数据均需要校验签名
加密要求 无论是请求数据还是返回的数据,都需要对data的内容进行AES对称加密
判断逻辑 先判断返回status状态,再去解析data内容

示例代码


import com.alibaba.fastjson.JSONObject;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.net.URI;
import java.util.HashMap;
import java.util.Map;

public class HttpClientUtil {
    /**
     * @param url     发送请求的 URL
     * @param jsonStr 需要post的数据
     * @param headers 请求头
     * @return 所代表远程资源的响应结果
     */
    public static String postParam(String url, String jsonStr, Map<String, String> headers) {
        HttpPost post = new HttpPost();
        HttpResponse response = null;
        try {
            post.setURI(new URI(url));
            if (StringUtils.isNotEmpty(jsonStr)) {
                post.setEntity(new StringEntity(jsonStr, "UTF-8"));
            }
            if (MapUtils.isNotEmpty(headers)) {
                for (Map.Entry<String, String> entry : headers.entrySet()) {
                    post.addHeader(entry.getKey(), entry.getValue());
                }
            }
            HttpClient httpClient = HttpClients.createDefault();
            response = httpClient.execute(post);
            return EntityUtils.toString(response.getEntity(), "UTF-8");
        } catch (Exception e) {
            throw new RuntimeException("got an error from HTTP for url:" + url, e);
        } finally {
            if (response != null) {
                EntityUtils.consumeQuietly(response.getEntity());
            }
            post.releaseConnection();
        }
    }

    public static void main(String[] args) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("data", "7ATCVdwZ3Jqk0aglNP4XGFiNS+1rXCeg21ctLGRQXw6h+cQEZVlyqCT+O8QWRQRVKqa+1N57EwBPLEYPq3eYnQ==");
        jsonObject.put("timeStamp", "1513158330");
        jsonObject.put("seq", "20171213174531");
        jsonObject.put("sign", "D4C86864BE69E26B2DF4DBC0EBF27237");
        //生成需要post的json字符串
        String jsonStr = jsonObject.toJSONString();
        //请求头
        Map<String, String> headers = new HashMap<>();
        headers.put("Content-Type", "application/json; charset=utf-8");
        //进行http的post请求
        System.out.println(postParam("http://test.com/queryToken", jsonStr, headers));
    }

}