public class SendToWX {
//获取token
String access_token = getToken();
//请求串
String url = SEND_MESSAGE_URL + access_token;
//拼接请求JSON字符串
StringBuffer stringBuffer = new StringBuffer();
stringBuffer.append("{");
stringBuffer.append(""msgid":""+msgid);
stringBuffer.append(""");
stringBuffer.append("}");
String json = stringBuffer.toString();
try {
URL postUrl = new URL(url);
HttpURLConnection http = (HttpURLConnection) postUrl.openConnection();
http.setRequestMethod("POST");
http.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
http.setDoOutput(true);
http.setDoInput(true);
// 连接超时30秒
System.setProperty("sun.net.client.defaultConnectTimeout", "30000");
// 读取超时30秒
System.setProperty("sun.net.client.defaultReadTimeout", "30000");
http.connect();
//写入内容
OutputStream outputStream = http.getOutputStream();
outputStream.write(json.getBytes("UTF-8"));
InputStream inputStream = http.getInputStream();
int size = inputStream.available();
byte[] jsonBytes = new byte[size];
//将腾讯返回的内容读入
inputStream.read(jsonBytes);
String message = new String(jsonBytes, "UTF-8");
JSonObject jsonObject = (JSONObject) JSONObject.parse(message);
System.out.println("微信返回的消息:" + jsonObject.toString());
//清空输出流
outputStream.flush();
//关闭输出通道
outputStream.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}