已经有了access_token了,希望通过hutool推送微信服务号信息

微信公众号 java 文章 2023-03-20 09:22 681 0 全屏看文

AI助手支持GPT4.0

既然你已经有了access_token,我们可以使用hutool工具库来发送消息。首先,请确保你的项目中已经添加了hutool-http依赖。以下是Maven和Gradle的依赖设置:

Maven:

<dependency>
    <groupId>cn.hutool</groupId>
    <artifactId>hutool-http</artifactId>
    <version>5.7.17</version>
</dependency>

然后,你可以使用以下代码来发送文本消息:

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;

public class WeChatService {

    private static final String SEND_MESSAGE_URL = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=";

    public static void main(String[] args) {
        String accessToken = "your_access_token";
        String openid = "user_openid";
        String message = "Hello, this is a message from WeChat Service Account!";
        sendMessage(accessToken, openid, message);
    }

    private static void sendMessage(String accessToken, String openid, String message) {
        String url = SEND_MESSAGE_URL + accessToken;
        JSONObject jsonMessage = createJsonMessage(openid, message);

        HttpResponse response = HttpRequest.post(url)
                .body(jsonMessage.toString())
                .execute();

        System.out.println("Send message response: " + response.body());
    }

    private static JSONObject createJsonMessage(String openid, String content) {
        JSONObject jsonMessage = JSONUtil.createObj();
        jsonMessage.put("touser", openid);
        jsonMessage.put("msgtype", "text");

        JSONObject textContent = JSONUtil.createObj();
        textContent.put("content", content);

        jsonMessage.put("text", textContent);
        return jsonMessage;
    }
}

请确保将your_access_token替换为你的实际access_token,以及将user_openid替换为实际的用户openid。此代码示例仅发送文本消息,你可以根据需要修改createJsonMessage方法以发送其他类型的消息。


-EOF-

AI助手支持GPT4.0