1. 程式人生 > >微信公眾號開發《傳送訊息模板到公眾號(java版)》

微信公眾號開發《傳送訊息模板到公眾號(java版)》

開發者工具獲取相關資訊
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();

    }

}

}