# 调用示例

  • 以发送公聊区消息为例
package com.kugou.fanxing.miniprogram.app.controller;


import com.alibaba.fastjson.JSON;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
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.ContentType;
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.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.security.MessageDigest;
import java.util.HashMap;
import java.util.Map;

public class OpenApiInvokeSample {

    private static final Logger LOGGER = LoggerFactory.getLogger(OpenApiInvokeSample.class);

    /**
     * 计算签名
     *
     * @param appId
     * @param time
     * @param queryString
     * @param body
     * @param nonce
     * @param secretKey
     * @return
     */
    public static String generalSign(String appId, String time, String queryString, String body, String nonce, String secretKey) {

        String sign = StringUtils.EMPTY;

        try {
            String toSignStr = appId + time + nonce + queryString + body + secretKey;
            MessageDigest digest = MessageDigest.getInstance("MD5");
            byte[] signBytes = toSignStr.getBytes("utf-8");
            digest.update(signBytes);
            sign = bytesToHex(digest.digest()); // 转成16进制字符串
        } catch (Exception e) {
            LOGGER.warn("generalSign error", e);
        }

        return sign;
    }

    public static String bytesToHex(byte[] bytes) {

        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < bytes.length; i++) {
            String hex = Integer.toHexString(0xFF & bytes[i]);
            if (hex.length() == 1) {
                sb.append('0');
            }
            sb.append(hex);
        }
        return sb.toString();
    }

    /**
     * 发送post请求
     *
     * @param url
     * @param headerMap
     * @param paramMap
     * @return
     */
    public static String executePost(String url, Map<String, Object> headerMap, Map<String, Object> paramMap) {

        CloseableHttpClient httpClient = HttpClients.createDefault();

        String postBody = JSON.toJSONString(paramMap);
        StringEntity entity = new StringEntity(postBody, "UTF-8");

        entity.setContentEncoding("UTF-8");
        entity.setContentType(ContentType.APPLICATION_JSON.getMimeType());

        HttpPost httpPost = new HttpPost(url);
        httpPost.setEntity(entity);

        RequestConfig requestConfig = RequestConfig.custom()
                .setConnectTimeout(3000)
                .setConnectionRequestTimeout(3000)
                .setSocketTimeout(3000)
                .build();

        httpPost.setConfig(requestConfig);

        if (MapUtils.isNotEmpty(headerMap)) {
            headerMap.forEach((key, value) -> httpPost.addHeader(key, value.toString()));
        }

        try (CloseableHttpResponse resp = httpClient.execute(httpPost)) {
            return EntityUtils.toString(resp.getEntity());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static void main(String[] args) {

        // 小程序appId
        String appId = "1b3a78327b514487bda2beef123fafa8";
        // 小程序secretKey
        String secretKey = "skgOiMNng6betaDw";
        // 当前时间戳
        String time = String.valueOf(System.currentTimeMillis());
        // 随机串
        String nonce = RandomStringUtils.randomAlphabetic(16);
        
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("id", "1365804735490061226_start");
        paramMap.put("content", "主播正在使用酷狗小程序");
        paramMap.put("starId", "qN7HzpbGl8z7uiezKDOv3Q==");
        paramMap.put("appId", appId);
        paramMap.put("time", time);

        String checkSum = generalSign(appId, time, "", JSON.toJSONString(paramMap), nonce, secretKey);

        Map<String, Object> headerMap = new HashMap<>();
        headerMap.put("SAppId", appId);
        headerMap.put("time", time);
        headerMap.put("nonce", nonce);
        headerMap.put("checkSum", checkSum);

        String resp = executePost("https://fx.service.kugou.com/fxservice/miniprogram/open/sendSysChatMsg", headerMap, paramMap);
        System.out.println(resp);
    }
}