String urlTest = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wxe********&secret=dbf8***********e8";
JSONObject jsonObject = AuthUtil.doGetJson(urlTest);
String token = jsonObject.getString("access_token");
System.out.println("============");
System.out.println(token);
System.out.println("============");
String url = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=" + token;//请求url
System.out.println("============");
System.out.println(url);
System.out.println("============");
String MSG = "{\r\n"
+ " \"touser\": \"oCasg6eC8RVsn-R11FIZNoZmJ7ZM\", \r\n"
+ " \"msgtype\": \"text\", \r\n"
+ " \"text\": {\r\n"
+ " \"content\": \"Hello World\"\r\n"
+ " }\r\n"
+ "}";//touser时openid
URL urlGet = null;
JSONObject object = null;
try {
urlGet = new URL(url);
HttpURLConnection http = (HttpURLConnection) urlGet.openConnection();
http.setRequestMethod("GET"); //必须get方式请求
http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
http.setDoOutput(true);
http.setDoInput(true);
System.setProperty("sun.net.client.defaultConnectTimeout", "30000");//连接超时3秒
System.setProperty("sun.net.client.defaultReadTimeout", "30000"); // 读取超时30秒
http.connect();
OutputStream os =null;
if(!MSG.equals("") ) { //写消息数据
os = http.getOutputStream();
os.write(MSG.getBytes("UTF-8")); //传入参数
}
InputStream is = http.getInputStream();
int size = is.available();
byte[] jsonBytes = new byte[ size ];
is.read(jsonBytes);
String message = new String(jsonBytes, "UTF-8");
object = JSONObject.parseObject(message);
System.out.println("=========");
System.out.println(object);
System.out.println("=========");
//关闭流
if(!MSG.equals("")) {
os.flush();
os.close();
}
is.close();
} catch (Exception e) {
e.printStackTrace();
}
微信公众平台接口调试工具:https://mp.weixin.qq.com/debug/
微信公众平台测试号管理:https://mp.weixin.qq.com/debug/cgi-bin/sandboxinfo?action=showinfo&t=sandbox/index