代码如下:
public static void main(String[] args) {
String token =WeiXinUtils.getAccessToken();
System.out.println("token = "+token);
// 组装要发送的数据
JSONObject body = new JSONObject();
// 要推给谁
body.put("touser", "xxxx");
// 模板ID
body.put("template_id", "xxxx");
JSONObject data = new JSONObject();
JSONObject data1 = new JSONObject();
data1.put("value", "当天12点");
data.put("character_string1", data1);
body.put("data", data);
System.out.println("data = "+body.toString());
String post = "";
try {
post = HttpClientUtils.sendPost("https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + token, body.toString());
}catch (Exception e){
System.out.println("eeee = "+e);
}
System.out.println("post = "+post);
}
public static String sendPost(String url, String data) throws Exception {
URL fullUrl = new URL(url);
HttpURLConnection connection = (HttpURLConnection) fullUrl.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/json");
connection.setRequestProperty("Accept", "application/json");
connection.setRequestProperty("Charset", "UTF-8");
connection.setRequestProperty("Content-Length", String.valueOf(data.length()));
connection.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
wr.writeBytes(data);
wr.flush();
wr.close();
if (connection.getResponseCode()!= 200) {
throw new RuntimeException("Failed : HTTP error code : " + connection.getResponseCode());
}
BufferedReader br = new BufferedReader(new InputStreamReader((connection.getInputStream())));
StringBuilder sb = new StringBuilder();
String output;
while ((output = br.readLine())!= null) {
sb.append(output);
}
connection.disconnect();
return sb.toString();
}
y已经设置了 utf-8 还是显示乱码,请教下如何解决
用resttemplate请求吧,代码简洁
你的代码,我在我本地运行不乱码
我本地不乱码,跟公众号没关系
我用你代码运行没问题,还不清楚问题在哪吗