Java 通过API 向微信公众号用户发送语音消息的步骤和代码实现

java 微信公众号 文章 2023-06-21 14:35 1175 0 全屏看文

AI助手支持GPT4.0

Java 实现向微信公众号用户发送语音消息的步骤和代码如下:


步骤:


1. 获取access_token:向微信服务器发送获取access_token的请求,获得access_token。access_token是调用微信接口的必备参数。


2. 上传语音文件:将本地的语音文件上传到微信服务器,获得media_id。


3. 发送语音消息:通过微信公众号的客服接口,向指定用户发送语音消息,将media_id作为语音消息的参数。


代码实现:

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.HashMap;
import java.util.Map;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
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.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;

public class SendVoiceMessage {

    private static final String APP_ID = "your_app_id";
    private static final String APP_SECRET = "your_app_secret";
    private static final String OPENID = "your_openid";
    private static final String FILE_PATH = "your_file_path";

    public static void main(String[] args) throws Exception {
        String accessToken = getAccessToken(APP_ID, APP_SECRET);
        String mediaId = uploadVoice(accessToken, new File(FILE_PATH));
        sendVoiceMessage(accessToken, OPENID, mediaId);
    }

    // 获取access_token
    private static String getAccessToken(String appId, String appSecret) throws Exception {
        String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appId + "&secret=" + appSecret;
        String response = httpGet(url);
        JSONObject jsonObject = new JSONObject(response);
        return jsonObject.getString("access_token");
    }

    // 上传语音文件
    private static String uploadVoice(String accessToken, File file) throws Exception {
        String url = "https://api.weixin.qq.com/cgi-bin/media/upload?access_token=" + accessToken + "&type=voice";
        MultipartEntityBuilder builder = MultipartEntityBuilder.create();
        builder.addBinaryBody("media", file, ContentType.APPLICATION_OCTET_STREAM, file.getName());
        HttpEntity multipart = builder.build();
        HttpPost httpPost = new HttpPost(url);
        httpPost.setEntity(multipart);
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse httpResponse = httpClient.execute(httpPost);
        String response = EntityUtils.toString(httpResponse.getEntity());
        JSONObject jsonObject = new JSONObject(response);
        return jsonObject.getString("media_id");
    }

    // 发送语音消息
    private static void sendVoiceMessage(String accessToken, String openid, String mediaId) throws Exception {
        String url = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=" + accessToken;
        Map<String, Object> message = new HashMap<>();
        message.put("touser", openid);
        message.put("msgtype", "voice");
        Map<String, String> voice = new HashMap<>();
        voice.put("media_id", mediaId);
        message.put("voice", voice);
        JSONObject jsonObject = new JSONObject(message);
        String response = httpPost(url, jsonObject.toString());
        System.out.println(response);
    }

    // 发送HTTP POST请求
    private static String httpPost(String url, String data) throws ClientProtocolException, IOException {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(url);
        httpPost.setEntity(new org.apache.http.entity.StringEntity(data, ContentType.APPLICATION_JSON));
        HttpResponse httpResponse = httpClient.execute(httpPost);
        return EntityUtils.toString(httpResponse.getEntity());
    }

    // 发送HTTP GET请求
    private static String httpGet(String url) throws ClientProtocolException, IOException {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpGet httpGet = new HttpGet(url);
        HttpResponse httpResponse = httpClient.execute(httpGet);
        return EntityUtils.toString(httpResponse.getEntity());
    }
}

其中,APP_ID和APP_SECRET是微信公众号的应用ID和应用密钥,OPENID是要发送语音消息的用户的openid,FILE_PATH是本地语音文件的路径。


-EOF-

AI助手支持GPT4.0