(6) Detailed explanation of interface interaction

This article introduces the complete interaction process of an interface request.

request parameters

easyopen defines 7 fixed parameters, which are received with json

{
    "name":"goods.get",
    "version":"2.0",
    "app_key":"test",
    "data":"%7B%22goods_name%22%3A%22iphone6%22%7D",    
    "format":"json",    
    "timestamp":"2018-01-16 17:02:02",
    "sign":"4CB446DF67DB3637500D4715298CE4A3"
}
  • name: interface name
  • version: interface version number
  • app_key: app_key assigned to the client
  • data: business parameters, json format and urlencode
  • format: return format, json, xml two
  • timestamp: timestamp, yyyy-MM-dd HH:mm:ss
  • sign: signature string

The sign needs to be generated using the signature algorithm agreed upon by both parties.

request method

The request data is placed in the body in json format. Here is a POST tool class:

public class PostUtil {

    private static final String UTF8 = "UTF-8";
    private static final String CONTENT_TYPE_JSON = "application/json";
    private static final String ACCEPT_LANGUAGE = "Accept-Language";


    /**
     * POST请求
     * @param url
     * @param params
     * @param lang 语言zh,en
     * @return
     * @throws Exception
     */
    public static String post(String url, JSONObject params, String lang) throws Exception {
        String encode = UTF8;
        // 使用 POST 方式提交数据
        PostMethod method = new PostMethod(url);
        try {
            String requestBody = params.toJSONString();
            // 请求数据放在body体中,采用json格式
            method.setRequestEntity(new StringRequestEntity(requestBody, CONTENT_TYPE_JSON, encode));
            // 设置请求语言
            method.setRequestHeader(ACCEPT_LANGUAGE, lang);

            HttpClient client = new HttpClient();
            int state = client.executeMethod(method); // 返回的状态

            if (state != HttpStatus.SC_OK) {
                throw new Exception("HttpStatus is " + state);
            }

            String response = method.getResponseBodyAsString();

            return response; // response就是最后得到的结果
        } catch (Exception e) {
            throw e;
        } finally {
            method.releaseConnection();
        }
    }

}
  • Request action code:
@Test
public void testGet() throws Exception {

    Map<String, String> param = new HashMap<String, String>();

    Goods goods = new Goods();
    String data = JSON.toJSONString(goods);
    data = URLEncoder.encode(data, "UTF-8");

    param.put("name", "hello");
    param.put("app_key", appId);
    param.put("data", data);
    param.put("timestamp", getTime());
    param.put("version", "");
    param.put("format", "json");

    String sign = ApiUtil.buildSign(param, secret);

    param.put("sign", sign);

    System.out.println("请求内容:" + JSON.toJSONString(param));

    String resp = PostUtil.post(url, param,"zh");

    System.out.println(resp);
}

public String getTime() {
    return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
}

Signature algorithm

The signature algorithm is described as follows:

  1. Sort request parameters in ascending order by parameter name;
  2. According to the request parameter name and parameter value, connect each other to form a string: <paramName1><paramValue1><paramName2><paramValue2>...;
  3. Add the application key to the head and tail of the above request parameter string: <secret><请求参数字符串><secret>;
  4. Perform MD5 operation on the string to get a binary array;
  5. Convert the binary array to a hexadecimal string (all uppercase), which is the signature corresponding to these request parameters;
  6. The signature value is sent to the service open platform together with other request parameters using the sign parameter.

Fake code:

Map<String,Object> paramsMap = new ...; // 参数

Set<String> keySet = paramsMap.keySet();
List<String> paramNames = new ArrayList<String>(keySet);
// 1. 
Collections.sort(paramNames);

StringBuilder paramNameValue = new StringBuilder();
// 2. 
for (String paramName : paramNames) {
    paramNameValue.append(paramName).append(paramsMap.get(paramName));
}
// 3.
String source = secret + paramNameValue.toString() + secret;
// 4.& 5.
String sign = md5(source);
// 6. 
paramsMap.put("sign",sign);

server-side verification

After the server gets the request data, it will verify the sign field. The verification steps are as follows:

  1. Get the secret saved by the server according to the app_key passed by the client
  2. After getting the secret, generate the serverSign of the server through the signature algorithm
  3. Compare whether the client sign and serverSign are equal. If they are equal, it proves that the data sent by the client is legal data, otherwise it will not return an error message.
  4. Process business and return results

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324929415&siteId=291194637
Recommended