微信公众号开发《发送消息模板到公众号(java版)》

来源:互联网 发布:java调用外部接口 编辑:程序博客网 时间:2024/04/30 00:03

开发者工具获取相关信息
appID+appsecret
openid+模板id

具体实现过程工具类测试:(使用前需要适当修改即可)
package com.shove.util;

import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import net.sf.json.JSONObject;

public class WeChatTUtil {
/**

 * 微信公共账号发送给账号 * @param content 文本内容 * @param toUser 微信用户   * @return */public  void sendTextMessageToUser(){

// String content=”{\”first\”: {\”value\”:\”尊敬的 wangzhiwei,您好\”}}”;
String json = “{\”template_id\”: \”Su9YTsUd5FfQNda4xsLruAv3IxTmZXX6F6G5vptMVDY\”,\”touser\”: \”ogQCf08aWuRmxl5HZCS03JeMjzJ0\”,\”msgtype\”: \”text\”, \”data\”:{\”first\”: {\”value\”:\”尊敬的 wangzhiwei,您好\”}}}”;

    //获取access_token    //       GetExistAccessToken getExistAccessToken = GetExistAccessToken.getInstance();    //       String accessToken = getExistAccessToken.getExistAccessToken();    String accessToken = getAccess_token();    System.out.println("**********************************"+accessToken);    //获取请求路径    String action = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token="+accessToken;    //                      "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$appid."&secret=".$secret."";    System.out.println("json:"+json);    try {        connectWeiXinInterface(action,json);    } catch (Exception e) {        e.printStackTrace();    }}/** * 获得ACCESS_TOKEN *  * @Title: getAccess_token * @Description: 获得ACCESS_TOKEN * @param @return 设定文件 * @return String 返回类型 * @throws */public  String getAccess_token() {    String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="            + "wx0ab188e12389a8bd"+ "&secret=" + "a63c60a3dbef49b66da8a8bde413aaff";    String accessToken = null;    try {        URL 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");// 连接超时30秒        System.setProperty("sun.net.client.defaultReadTimeout", "30000"); // 读取超时30秒        http.connect();        InputStream is = http.getInputStream();        int size = is.available();        byte[] jsonBytes = new byte[size];        is.read(jsonBytes);        String message = new String(jsonBytes, "UTF-8");        JSONObject demoJson = JSONObject.fromObject(message);        accessToken = demoJson.getString("access_token");        System.out.println(accessToken);        is.close();    } catch (Exception e) {        e.printStackTrace();    }    return accessToken;}/** * 连接请求微信后台接口 * @param action 接口url * @param json  请求接口传送的json字符串 */public  void connectWeiXinInterface(String action,String json){    URL url;    try {        url = new URL(action);        HttpURLConnection http = (HttpURLConnection) url.openConnection();        http.setRequestMethod("POST");        http.setRequestProperty("Content-Type",                "application/x-www-form-urlencoded");        http.setDoOutput(true);        http.setDoInput(true);        System.setProperty("sun.net.client.defaultConnectTimeout", "30000");// 连接超时30秒        System.setProperty("sun.net.client.defaultReadTimeout", "30000"); // 读取超时30秒        http.connect();        OutputStream os = http.getOutputStream();        os.write(json.getBytes("UTF-8"));// 传入参数        InputStream is = http.getInputStream();        int size = is.available();        byte[] jsonBytes = new byte[size];        is.read(jsonBytes);        String result = new String(jsonBytes, "UTF-8");        System.out.println("请求返回结果:"+result);        os.flush();        os.close();    } catch (Exception e) {        e.printStackTrace();    }}

}