微信公众号推送消息-Java

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值