1. 程式人生 > >Java呼叫微信客服訊息介面

Java呼叫微信客服訊息介面

package com.yhxc.utils.wechat;

import net.sf.json.JSONObject;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;

/**
 * @Author: 趙賀飛
 * @Date: 2018/3/28 16:05
 * 呼叫微信公眾平臺主動發訊息介面
 */
public class wechat {

    public static void main(String[] args) throws IOException {

        //元泓星辰
        String appId = APPID;
        String appSecret = appSecret;
        String token = getAccess_token(appId, appSecret).getString("access_token");
        System.err.println("Tocken:" + token);

        //傳送訊息
        /*JSONObject text = new JSONObject();
        text.element("content", "內容");
        JSONObject json = new JSONObject();
        json.element("touser", "oNLtTw6H2Rx5Qg-SWaEjsbKfPkGY");
        json.element("text", text);
        json.element("msgtype", "text");*/
       // customSend(json, token);

        //傳送圖片
        /*JSONObject media_id = new JSONObject();
        String filePath = "E:\\SougouImages\\SogouWP\\Net\\WallPaper\\405376.jpg";
        media_id.element("media_id", upload(filePath, token, "image"));
        JSONObject json1 = new JSONObject();
        json1.element("touser", "oNLtTw6H2Rx5Qg-SWaEjsbKfPkGY");
        json1.element("image", media_id);
        json1.element("msgtype", "image");
        customSend(json1, token);*/
    }

    /**
     * 獲取code
     */
    //https://open.weixin.qq.com/connect/oauth2/authorize?appid=APPID&redirect_uri=redirect_uri&response_type=code&scope=snsapi_base&state=1&connect_redirect=1#wechat_redirect

    /**
     * 獲取code後,根據code獲取openid
     */
    //https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=secret&code=$code&grant_type=authorization_code


    /**
     * 傳送圖片
     * @param filePath
     * @param accessToken
     * @param type
     * @return
     * @throws IOException
     */
    public static String upload(String filePath, String accessToken, String type) throws IOException {
        File file = new File(filePath);
        if (!file.exists() || !file.isFile()) {
            throw new IOException("檔案不存在");
        }
        //String url = UPLOAD_URL.replace("ACCESS_TOKEN", accessToken).replace("TYPE", type);
        String url = "https://api.weixin.qq.com/cgi-bin/media/upload?access_token="+ accessToken +"&type="+ type;
        URL urlobj = new URL(url);
        HttpURLConnection conn = (HttpURLConnection) urlobj.openConnection();
        conn.setRequestMethod("POST");
        conn.setDoInput(true);
        conn.setDoOutput(true);
        conn.setUseCaches(false);

        //設定頭資訊
        conn.setRequestProperty("Connection", "Keep-Alive");
        conn.setRequestProperty("Charset", "UTF-8");

        //設定邊界
        String BOUNFARY = "----------" + System.currentTimeMillis();
        conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + BOUNFARY);

        StringBuilder sb = new StringBuilder();
        sb.append("--");
        sb.append(BOUNFARY);
        sb.append("\r\n");
        sb.append("Content-Disposition:from-data;name=\"file\";filename=\"" + file.getName() + "\"\r\n");
        sb.append("Content-Type:application/actet-stream\r\n\r\n");

        byte[] head = sb.toString().getBytes("utf-8");
        //獲得輸出流
        OutputStream out = new DataOutputStream(conn.getOutputStream());
        //輸出表頭
        out.write(head);

        //檔案正文部分
        //把檔案以流的方式 推入到url
        DataInputStream in = new DataInputStream(new FileInputStream(file));
        int bytes = 0;
        byte[] bufferOut = new byte[1024];
        while ((bytes = in.read(bufferOut)) != -1) {
            out.write(bufferOut, 0, bytes);
        }
        in.close();
        //結尾部分
        byte[] foot = ("\r\n--" + BOUNFARY + "--\r\n").getBytes("utf-8");
        out.write(foot);
        out.flush();
        out.close();

        StringBuffer buffer = new StringBuffer();
        BufferedReader reader = null;
        String result = null;
        reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        String line = null;
        while ((line = reader.readLine()) != null) {
            buffer.append(line);
        }
        if (result == null) {
            result = buffer.toString();
        }
        if (result != null) {
            reader.close();
        }
        JSONObject jsonObject = JSONObject.fromObject(result);
        System.out.println(jsonObject);
        String typeName = "media_id";
        if (!"image".equals(type) && !"voice".equals(type) && !"video".equals(type)) {
            typeName = type + "_media_id";
        }
        String mediaid = jsonObject.getString(typeName);
        return mediaid;
    }


    /**
     * post請求,傳送訊息
     */
    public static void customSend(JSONObject json, String accessToken) {

        PrintWriter out = null;
        BufferedReader in = null;
        String result = "";
        try {
            URL realUrl = new URL("https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=" + accessToken);
            // 開啟和URL之間的連線
            URLConnection conn = realUrl.openConnection();
            // 設定通用的請求屬性
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            // 傳送POST請求必須設定如下兩行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            // 獲取URLConnection物件對應的輸出流
            out = new PrintWriter(conn.getOutputStream());
            // 傳送請求引數
            out.print(json.toString());
            // flush輸出流的緩衝
            out.flush();
            // 定義BufferedReader輸入流來讀取URL的響應
            in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
            System.out.println("客服訊息result:" + result);
        } catch (Exception e) {
            System.out.println("向客服傳送 POST 請求出現異常!" + e);
            e.printStackTrace();
        }
        //使用finally塊來關閉輸出流、輸入流
        finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    }


    /**
     * 獲取token
     *
     * @return
     */
    public static JSONObject getAccess_token(String appId, String appSecret) {
        String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appId + "&secret=" + appSecret;
        String accessToken = null;
        JSONObject jsonObj = 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);
            accessToken = new String(jsonBytes, "UTF-8");
            System.err.println(accessToken);
            jsonObj = JSONObject.fromObject(accessToken);
            is.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return jsonObj;
    }
}