Java实现微信群发消息

1.整体流程

在实现微信群发消息的过程中,可以分为以下几个步骤:

步骤 描述
1 获取微信公众号的access_token
2 获取群发消息的openids
3 构建消息内容
4 发送群发消息

下面将逐步介绍每个步骤所需的代码和注意事项。

2.获取微信公众号的access_token

在进行微信群发消息之前,首先需要获取微信公众号的access_token。access_token是访问微信公众号接口的凭证,具有一定的时效性,一般为两小时。可以通过以下代码获取access_token:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class AccessTokenUtil {
    // 微信公众号的AppID和AppSecret
    private static final String APP_ID = "your_app_id";
    private static final String APP_SECRET = "your_app_secret";

    public static void main(String[] args) {
        String accessToken = getAccessToken();
        System.out.println("Access Token: " + accessToken);
    }

    public static String getAccessToken() {
        String accessToken = null;
        String url = " + APP_ID + "&secret=" + APP_SECRET;

        try {
            URL accessTokenUrl = new URL(url);
            HttpURLConnection connection = (HttpURLConnection) accessTokenUrl.openConnection();
            connection.setRequestMethod("GET");
            connection.setDoOutput(true);

            InputStream stream = connection.getInputStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(stream));
            StringBuilder builder = new StringBuilder();
            String line;

            while ((line = reader.readLine()) != null) {
                builder.append(line);
            }

            JSONObject jsonObject = new JSONObject(builder.toString());
            accessToken = jsonObject.getString("access_token");
        } catch (IOException e) {
            e.printStackTrace();
        }

        return accessToken;
    }
}

需要替换APP_IDAPP_SECRET为自己微信公众号的AppID和AppSecret。

3.获取群发消息的openids

在群发消息之前,需要获取要发送消息的用户的openids。可以通过以下代码获取openids:

public class OpenidUtil {
    // 微信公众号的access_token
    private static final String ACCESS_TOKEN = "your_access_token";

    public static void main(String[] args) {
        List<String> openids = getOpenids();
        for (String openid : openids) {
            System.out.println(openid);
        }
    }

    public static List<String> getOpenids() {
        List<String> openids = new ArrayList<>();
        String url = " + ACCESS_TOKEN;

        try {
            URL openidUrl = new URL(url);
            HttpURLConnection connection = (HttpURLConnection) openidUrl.openConnection();
            connection.setRequestMethod("GET");
            connection.setDoOutput(true);

            InputStream stream = connection.getInputStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(stream));
            StringBuilder builder = new StringBuilder();
            String line;

            while ((line = reader.readLine()) != null) {
                builder.append(line);
            }

            JSONObject jsonObject = new JSONObject(builder.toString());
            JSONObject data = jsonObject.getJSONObject("data");
            JSONArray openidArray = data.getJSONArray("openid");

            for (int i = 0; i < openidArray.length(); i++) {
                openids.add(openidArray.getString(i));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        return openids;
    }
}

同样需要替换ACCESS_TOKEN为之前获取到的access_token。

4.构建消息内容

在进行微信群发消息时,需要构建消息的内容。可以通过以下代码构建消息内容:

public class MessageUtil {
    // 微信公众号的access_token
    private static final String ACCESS_TOKEN = "your_access_token";

    public static void main(String[] args) {
        List<String> openids = getOpenids();
        String message = buildMessage();
        sendGroupMessage(openids, message);
    }

    public static String buildMessage() {
        // 构建图文消息
        StringBuilder messageBuilder = new StringBuilder();
        messageBuilder.append("<xml>");
        messageBuilder.append("<ToUserName><![CDATA[ToUser]]></ToUserName>");
        messageBuilder.append("<FromUserName><![CDATA[FromUser]]></FromUserName>");
        messageBuilder.append("<CreateTime>12345678</CreateTime>");
        messageBuilder.append("<MsgType><![CDATA[news]]></MsgType>");
        messageBuilder.append("<ArticleCount>1</ArticleCount>");
        messageBuilder.append("<Articles