首先根据微信文档上给定的数据结构创建一个消息类实体:
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();
}
}