微信开发---发送客服消息

本文介绍了在微信开发中发送客服消息的步骤和遇到的问题。通过创建KFMessage类并实现发送方法,重点解决了POST请求时出现的44002错误,即empty post data问题。关键在于正确使用OutputStream的write方法写入JSON格式的消息对象,并确保使用utf-8编码防止中文乱码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

首先根据微信文档上给定的数据结构创建一个消息类实体:

public class KFMessage {

private String touser;
private String msgtype;
private MsgInfo text;


public KFMessage(String touser, String msgtype, String content) {
    super();
    this.touser = touser;
    this.msgtype = msgtype;
    text = new MsgInfo(content);
}
public String getTouser() {
    return touser;
}
public void setTouser(String touser) {
    this.touser = touser;
}
public String getMsgtype() {
    return msgtype;
}
public void setMsgtype(String msgtype) {
    this.msgtype = msgtype;
}
public MsgInfo getText() {
    return text;
}
public void setText(MsgInfo text) {
    this.text = text;
}

class MsgInfo{
    String content;

    public MsgInfo(String content) {
        super();
        this.content = content;
    }
}

}

然后就是发送客服消息的方法了,这里遇到的问题就是在向微信服务器post消息实体的时候一直post失败,失败的原因是把OutputStream 对象进行了包装,write了字符串,导致一直报44002,empty post data 的错误,其实什么都不用做,直接调用OutputStream 的write(Bytes byte)方法,把json格式的消息对象getBytes(“utf-8”)一下就可以了,注意,utf-8一定不能省,否则中文会乱码:
public static void replyKFMsg(String toUser,String msg) {

    try {
        URL url = new URL("https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token="+wxToken);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Charset", "UTF-8");
        connection.setRequestProperty("contentType", "application/json");
        connection.setRequestProperty("connection", "keep-alive");
        connection.setDoOutput(true);   
        connection.setDoInput(true);
        connection.connect();
        OutputStream out = connection.getOutputStream();  
        KFMessage kfMsg = new KFMessage(toUser, "text", msg);
        Gson g = new Gson();
        out.write(g.toJson(kfMsg).getBytes());

connection.disconnect();
} catch (Exception e) {
e.printStackTrace();
}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值