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

java 微信公众号 文章 2023-06-21 14:35 1501 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


国内超级便宜服务器

摸鱼人热门新闻聚合

钻级赞助商 我要加入

开发者在线工具

第三方支付技术请加QQ群

相关文章
HttpClient如何进行表单提交呢?
lambda表达式,将对象按照属性A作为 key,对象作为值 转成map对象
零基础学Java(10)面向对象-使用LocalDate类完成日历设计
intellij idea 2023 tomcat配置
java具有哪些新特性呢?
随便看看
教育科技公司申请微信支付被拒绝? 4798
微信公众号免300认证教程 5892
小程序已经上线,作为管理员无法在小程序数据助手查看数据? 5299
小程序广告组件通过审核,但是小程序内没有显示广告? 5067
企业微信通讯录账号被管理员误/恶意删除,怎么办? 9568
问题? 9047
如何快速搭建抽奖助手小程序(无需代码知识) 6177
许涛 大哥在吗, 要解冻小程序的时候提示信息主体不一致, 能帮忙看下吗? 7471
小程序搜一搜全称搜索不显示 麻烦解决一下!谢谢 6793
我的小程序广告收款主体是个体工商户,每个月邮寄两次发票很是麻烦,我年底的时候打包邮寄一次可以么? 6127