下面方法是在Java里面请求微信公众平台的一个主动发送消息的接口,但是里面有汉字,我在微信客户端查看消息时,是乱码
下面是微信公众平台网页版测试接口,测试不是乱码,
下面是微信客户端的效果图
本来打算用HttpClient,但是貌似构造不出这种JSON多层次的参数,所以就没用。
private static void readContentFromPost(String openId) throws IOException {
// Post请求的url,与get不同的是不需要带参数
String url = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=......";
// String url = "http://localhost:8080/WXGZPOT/MainServlet";
URL postUrl = new URL(url);
// 打开连接
HttpURLConnection connection = (HttpURLConnection) postUrl
.openConnection();
// 打开读写属性,默认均为false
connection.setDoOutput(true);
connection.setDoInput(true);
// 设置请求方式,默认为GET
connection.setRequestMethod("POST");
// Post 请求不能使用缓存
connection.setUseCaches(false);
connection.setInstanceFollowRedirects(true);
connection.addRequestProperty("Content-Type",
"application/x-www-form-urlencoded; encoding=utf-8");
DataOutputStream out = new DataOutputStream(
connection.getOutputStream());
// 正文内容其实跟get的URL中'?'后的参数字符串一致
JSONObject json = new JSONObject();
JSONObject json1 = new JSONObject();
JSONObject json2 = new JSONObject();
json2.put("title", "视频消息");
json2.put("description", "来自车机的实时状态视频");
json2.put("url", "ddds");
json2.put("picurl", "sdsd");
JSONArray array = new JSONArray();
array.add(json2);
json1.put("articles", array);
json.put("touser", openId);
json.put("msgtype", "news");
json.put("news", json1);
String content = json.toString();
System.out.println(content);
out.writeBytes(content);
out.flush();
out.close(); // flush and close
BufferedReader reader = new BufferedReader(new InputStreamReader(
connection.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
reader.close();
}
public static void main(String[] args) {
try {
readContentFromPost("orb0ot7iX6Mq_Scr0wh0vb8ExIfY");
} catch (IOException e) {
e.printStackTrace();
}
}