HttpUrlConnection乱码问题(求高手)

juenice 2015-03-16 11:20:33
下面方法是在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();
}
}
...全文
139 1 打赏 收藏 转发到动态 举报
写回复
用AI写文章
1 条回复
切换为时间正序
请发表友善的回复…
发表回复
tianfang 2015-03-16
  • 打赏
  • 举报
回复
out.writeBytes(content); 改为 out.write(content.getBytes(Charset.forName("utf-8"))); 试试

67,515

社区成员

发帖
与我相关
我的任务
社区描述
J2EE只是Java企业应用。我们需要一个跨J2SE/WEB/EJB的微容器,保护我们的业务核心组件(中间件),以延续它的生命力,而不是依赖J2SE/J2EE版本。
社区管理员
  • Java EE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧