微信公衆號開發(三、創建自定義菜單)

package com.jxq.weixin.servlet;

import java.util.HashMap;
import java.util.Map;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;


public class MenuMain {
    public static void main(String[] args) {
        ClickButton cbt=new ClickButton();
        cbt.setKey("image");
        cbt.setName("回覆圖片");
        cbt.setType("click");
         
         
        ViewButton vbt=new ViewButton();
        vbt.setUrl("http://www.ylcloudcastle.cn/ytw/index.html");
        vbt.setName("雲屯網");
        vbt.setType("view");
        
        ViewButton vbt1=new ViewButton();
        vbt1.setUrl("http://www.ylcloudcastle.cn/ytw/ytw/excellentstorelist_body.html");
        vbt1.setName("入駐企業");
        vbt1.setType("view");
        
        ViewButton vbt2=new ViewButton();
        vbt2.setUrl("http://www.ylcloudcastle.cn/ytw/ytw/contactUs.html");
        vbt2.setName("關於我們");
        vbt2.setType("view");
        
         
        JSONArray sub_button=new JSONArray();
        sub_button.add(vbt2);
         
         
        JSONObject buttonOne=new JSONObject();
        buttonOne.put("name", "關於我們");
        buttonOne.put("sub_button", sub_button);
         
        JSONArray button=new JSONArray();
        button.add(vbt);
        button.add(vbt1);
        button.add(vbt2);
//        button.add(buttonOne);
//        button.add(cbt);
         
        JSONObject menujson=new JSONObject();
        menujson.put("button", button);
        System.out.println(menujson);
        
        //樣例:https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wx56fa7dc91312bac8&secret=6be7387f78044cb39dfe654a177907e2
        Map<String,String> params=new HashMap<String, String>();
        params.put("grant_type", "client_credential");
        params.put("appid", "wx56fa7dc91312bac8");
        params.put("secret", "6be7387f78044cb39dfe654a177907e2");

        
        try {
            //獲取訪問微信服務器的access_token
            String token_json = HttpUtils.sendGet("https://api.weixin.qq.com/cgi-bin/token", params);
            JSONObject jo = JSONObject.fromObject(token_json);
            String access_token=jo.get("access_token").toString();

            System.out.println(token_json);
            System.out.println(access_token);
            //調用創建微信菜單接口,創建菜單。
            String url_createmenu="https://api.weixin.qq.com/cgi-bin/menu/create?access_token="+access_token;
            System.out.println("url_createmenu:"+url_createmenu);
            String rs=HttpUtils.sendPostBuffer(url_createmenu, menujson.toString());

            System.out.println("成功");
            System.out.println(rs);
        }catch(Exception e){
            System.out.println("請求錯誤!");
        }
     
    }

}

 

 

package com.jxq.weixin.servlet;

    import java.io.BufferedInputStream;
    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.InputStreamReader;
    import java.io.OutputStreamWriter;
    import java.net.MalformedURLException;
    import java.net.URI;
    import java.net.URL;
    import java.net.URLConnection;
    import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
    import java.util.Map;
    import java.util.Set;
    import java.util.zip.GZIPInputStream;
     
    import org.apache.http.HttpResponse;
    import org.apache.http.NameValuePair;
    import org.apache.http.client.ClientProtocolException;
    import org.apache.http.client.HttpClient;
    import org.apache.http.client.entity.UrlEncodedFormEntity;
    import org.apache.http.client.methods.HttpGet;
    import org.apache.http.client.methods.HttpPost;
    import org.apache.http.entity.StringEntity;
    import org.apache.http.impl.client.DefaultHttpClient;
    import org.apache.http.message.BasicNameValuePair;
    import org.apache.http.protocol.HTTP;
    import org.apache.http.util.EntityUtils;
import org.apache.taglibs.standard.tei.ForEachTEI;
     
    /**
     * ClassName: HttpUtils
     * 
     * @Description: http請求工具類
     * @author dapengniao
     * @date 2016年3月10日 下午3:57:14
     */
    @SuppressWarnings("deprecation")
    public class HttpUtils {
        /**
         * @Description: http get請求共用方法
         * @param @param reqUrl
         * @param @param params
         * @param @return
         * @param @throws Exception
         * @author dapengniao
         * @date 2016年3月10日 下午3:57:39
         */
        @SuppressWarnings("resource")
        public static String sendGet(String reqUrl, Map<String, String> params)
                throws Exception {
            InputStream inputStream = null;
            HttpGet request = new HttpGet();
            try {
                String url = buildUrl(reqUrl, params);
                HttpClient client = new DefaultHttpClient();
     
                //request.setHeader("Accept-Encoding", "gzip");
                //request.setHeader("content-type", "text/html");
                request.setURI(new URI(url));
     
                HttpResponse response = client.execute(request);
     
                inputStream = response.getEntity().getContent();
                String result = getJsonStringFromGZIP(inputStream);
                return result;
            } finally {
                if (inputStream != null) {
                    inputStream.close();
                }
                request.releaseConnection();
            }
     
        }
     
        /**
         * @Description: http post請求共用方法
         * @param @param reqUrl
         * @param @param params
         * @param @return
         * @param @throws Exception
         * @author dapengniao
         * @date 2016年3月10日 下午3:57:53
         */
        @SuppressWarnings("resource")
        public static String sendPost(String reqUrl, Map<String, String> params)
                throws Exception {
            try {
                Set<String> set = params.keySet();
                List<NameValuePair> list = new ArrayList<NameValuePair>();
                for (String key : set) {
                    list.add(new BasicNameValuePair(key, params.get(key)));
                }
                if (list.size() > 0) {
                    try {
                        HttpClient client = new DefaultHttpClient();
                        HttpPost request = new HttpPost(reqUrl);
     
                        request.setHeader("Accept-Encoding", "gzip");
                        request.setEntity(new UrlEncodedFormEntity(list, HTTP.UTF_8));
     
                        HttpResponse response = client.execute(request);
     
                        InputStream inputStream = response.getEntity().getContent();
                        try {
                            String result = getJsonStringFromGZIP(inputStream);
     
                            return result;
                        } finally {
                            inputStream.close();
                        }
                    } catch (Exception ex) {
                        ex.printStackTrace();
                        throw new Exception("網絡連接失敗,請連接網絡後再試");
                    }
                } else {
                    throw new Exception("參數不全,請稍後重試");
                }
            } catch (Exception ex) {
                ex.printStackTrace();
                throw new Exception("發送未知異常");
            }
        }
     
        /**
         * @Description: http post請求json數據
         * @param @param urls
         * @param @param params
         * @param @return
         * @param @throws ClientProtocolException
         * @param @throws IOException
         * @author dapengniao
         * @date 2016年3月10日 下午3:58:15
         */
        public static String sendPostBuffer(String urls, String params)
                throws ClientProtocolException, IOException {
            HttpPost request = new HttpPost(urls);
     
            StringEntity se = new StringEntity(params, HTTP.UTF_8);
            request.setEntity(se);
            // 發送請求
            @SuppressWarnings("resource")
            HttpResponse httpResponse = new DefaultHttpClient().execute(request);
            // 得到應答的字符串,這也是一個 JSON 格式保存的數據
            String retSrc = EntityUtils.toString(httpResponse.getEntity());
            request.releaseConnection();
            return retSrc;
     
        }
     
        /**
         * @Description: http請求發送xml內容
         * @param @param urlStr
         * @param @param xmlInfo
         * @param @return
         * @author dapengniao
         * @date 2016年3月10日 下午3:58:32
         */
        public static String sendXmlPost(String urlStr, String xmlInfo) {
            // xmlInfo xml具體字符串
     
            try {
                URL url = new URL(urlStr);
                URLConnection con = url.openConnection();
                con.setDoOutput(true);
                con.setRequestProperty("Pragma:", "no-cache");
                con.setRequestProperty("Cache-Control", "no-cache");
                con.setRequestProperty("Content-Type", "text/xml");
                OutputStreamWriter out = new OutputStreamWriter(
                        con.getOutputStream());
                out.write(new String(xmlInfo.getBytes("utf-8")));
                out.flush();
                out.close();
                BufferedReader br = new BufferedReader(new InputStreamReader(
                        con.getInputStream()));
                String lines = "";
                for (String line = br.readLine(); line != null; line = br
                        .readLine()) {
                    lines = lines + line;
                }
                return lines; // 返回請求結果
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return "fail";
        }
     
        private static String getJsonStringFromGZIP(InputStream is) {
            String jsonString = null;
            try {
                BufferedInputStream bis = new BufferedInputStream(is);
                bis.mark(2);
                // 取前兩個字節
                byte[] header = new byte[2];
                int result = bis.read(header);
                // reset輸入流到開始位置
                bis.reset();
                // 判斷是否是GZIP格式
                int headerData = getShort(header);
                // Gzip 流 的前兩個字節是 0x1f8b
                if (result != -1 && headerData == 0x1f8b) {
                    // LogUtil.i("HttpTask", " use GZIPInputStream  ");
                    is = new GZIPInputStream(bis);
                } else {
                    // LogUtil.d("HttpTask", " not use GZIPInputStream");
                    is = bis;
                }
                InputStreamReader reader = new InputStreamReader(is, "utf-8");
                char[] data = new char[100];
                int readSize;
                StringBuffer sb = new StringBuffer();
                while ((readSize = reader.read(data)) > 0) {
                    sb.append(data, 0, readSize);
                }
                jsonString = sb.toString();
                bis.close();
                reader.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
     
            return jsonString;
        }
     
        private static int getShort(byte[] data) {
            return (data[0] << 8) | data[1] & 0xFF;
        }
     
        /**
         * 構建get方式的url
         * 
         * @param reqUrl
         *            基礎的url地址
         * @param params
         *            查詢參數
         * @return 構建好的url
         */
        public static String buildUrl(String reqUrl, Map<String, String> params) {
            StringBuilder query = new StringBuilder();
            Set<String> set = params.keySet();

            int i=0;
            for (String key : set) {
                if(i>=params.size()-1)
                    query.append(String.format("%s=%s", key, params.get(key)));
                else 
                    query.append(String.format("%s=%s&", key, params.get(key)));
                i++;
            }
            return reqUrl + "?" + query.toString();
        }
}
 

 

package com.jxq.weixin.servlet;

public class ViewButton {
    private String type;
    private String name;
    private String url;
 
    public String getType() {
        return type;
    }
 
    public void setType(String type) {
        this.type = type;
    }
 
    public String getName() {
        return name;
    }
 
    public void setName(String name) {
        this.name = name;
    }
 
    public String getUrl() {
        return url;
    }
 
    public void setUrl(String url) {
        this.url = url;
    }
 
}

 

 

package com.jxq.weixin.servlet;

public class ClickButton {
    private String type;
    private String name;
    private String key;
 
    public String getType() {
        return type;
    }
 
    public void setType(String type) {
        this.type = type;
    }
 
    public String getName() {
        return name;
    }
 
    public void setName(String name) {
        this.name = name;
    }
 
    public String getKey() {
        return key;
    }
 
    public void setKey(String key) {
        this.key = key;
    }
}
 

 

package com.jxq.weixin.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Arrays;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class Signature extends HttpServlet {
    //token
    private final String token = "fengzheng";
     
    /**
         * Constructor of the object.
         */
    public Signature() {
        super();
    }

    /**
         * Destruction of the servlet. <br>
         */
    public void destroy() {
        super.destroy(); // Just puts "destroy" string in log
        // Put your code here
    }

    /**
         * The doGet method of the servlet. <br>
         *
         * This method is called when a form has its tag value method equals to get.
         * 
         * @param request the request send by the client to the server
         * @param response the response send by the server to the client
         * @throws ServletException if an error occurred
         * @throws IOException if an error occurred
         */
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        
        System.out.println("微信公衆號,開始簽名校驗");
        String signature = request.getParameter("signature")==null?"":request.getParameter("signature").toString();
        String timestamp = request.getParameter("timestamp")==null?"":request.getParameter("timestamp").toString();
        String nonce = request.getParameter("nonce")==null?"":request.getParameter("nonce").toString();
        String echostr = request.getParameter("echostr")==null?"":request.getParameter("echostr").toString();
     
        ArrayList<String> array = new ArrayList<String>();
        array.add(signature);
        array.add(timestamp);
        array.add(nonce);
     
        //原理:微信服務器發送上述4個參數給自己的程序,由自己的程序按照算法生成加密字符串,與微信服務器傳過來的簽名進行比對。
        //如果相同,則返回微信服務器結果。把echostr參數的內容原封不動回傳微信服務器。雙方完成握手,即表示對接成功。
        
        //使用微信服務器發過來的timestamp,nonce參數和自定義的token組合,使用sha1加密算法生成字符串,然後與微信服務器發過來的signature參數進行比對。
        //排序,
        String sortString = sort(token, timestamp, nonce);
        //加密
        String mytoken = SHA1(sortString);
        //校驗簽名
        if (mytoken != null && mytoken != "" && mytoken.equals(signature)) {
            System.out.println("微信公衆號,簽名校驗通過。");
            response.getWriter().println(echostr); //如果檢驗成功輸出echostr,微信服務器接收到此輸出,纔會確認檢驗完成。
        } else {
            System.out.println("微信公衆號,簽名校驗失敗。");
        }
    }

    /**
         * The doPost method of the servlet. <br>
         *
         * This method is called when a form has its tag value method equals to post.
         * 
         * @param request the request send by the client to the server
         * @param response the response send by the server to the client
         * @throws ServletException if an error occurred
         * @throws IOException if an error occurred
         */
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
        out.println("<HTML>");
        out.println("  <HEAD><TITLE>A Servlet</TITLE></HEAD>");
        out.println("  <BODY>");
        out.print("    This is ");
        out.print(this.getClass());
        out.println(", using the POST method");
        out.println("  </BODY>");
        out.println("</HTML>");
        out.flush();
        out.close();
    }

    /**
         * Initialization of the servlet. <br>
         *
         * @throws ServletException if an error occurs
         */
    public void init() throws ServletException {
        // Put your code here
    }

    /**
     * 排序方法
     * @param token
     * @param timestamp
     * @param nonce
     * @return
     */
    public static String sort(String token, String timestamp, String nonce) {
        String[] strArray = { token, timestamp, nonce };
        Arrays.sort(strArray);
     
        StringBuilder sbuilder = new StringBuilder();
        for (String str : strArray) {
            sbuilder.append(str);
        }
     
        return sbuilder.toString();
    }

    
    public static String SHA1(String decript) {
        try {
            MessageDigest digest = MessageDigest
                    .getInstance("SHA-1");
            digest.update(decript.getBytes());
            byte messageDigest[] = digest.digest();
            // Create Hex String
            StringBuffer hexString = new StringBuffer();
            // 字節數組轉換爲 十六進制 數
            for (int i = 0; i < messageDigest.length; i++) {
                String shaHex = Integer.toHexString(messageDigest[i] & 0xFF);
                if (shaHex.length() < 2) {
                    hexString.append(0);
                }
                hexString.append(shaHex);
            }
            return hexString.toString();
 
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return "";
    }

}
 

jar包:

運行結果:

log4j:WARN No appenders could be found for logger (org.apache.commons.beanutils.converters.BooleanConverter).
log4j:WARN Please initialize the log4j system properly.
log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.
{"button":[{"name":"雲屯網","type":"view","url":"http://www.ylcloudcastle.cn/ytw/index.html"},{"name":"入駐企業","type":"view","url":"http://www.ylcloudcastle.cn/ytw/ytw/excellentstorelist_body.html"},{"name":"關於我們","type":"view","url":"http://www.ylcloudcastle.cn/ytw/ytw/contactUs.html"}]}
{"access_token":"20_OL1dRXy-TGMjfydwwpRnq0NqHhCe97X7MXYOsmllpKh7l-jQwsAq384vahruOppEzOpj-vxtk3a2McuAwpCJjQfbFZTkMi2zAaL14CFtG581Q9R0bNyzZL0BcL1it9PZRiR_E0lXGme7JsuMWVCeAJAKJQ","expires_in":7200}
20_OL1dRXy-TGMjfydwwpRnq0NqHhCe97X7MXYOsmllpKh7l-jQwsAq384vahruOppEzOpj-vxtk3a2McuAwpCJjQfbFZTkMi2zAaL14CFtG581Q9R0bNyzZL0BcL1it9PZRiR_E0lXGme7JsuMWVCeAJAKJQ
url_createmenu:https://api.weixin.qq.com/cgi-bin/menu/create?access_token=20_OL1dRXy-TGMjfydwwpRnq0NqHhCe97X7MXYOsmllpKh7l-jQwsAq384vahruOppEzOpj-vxtk3a2McuAwpCJjQfbFZTkMi2zAaL14CFtG581Q9R0bNyzZL0BcL1it9PZRiR_E0lXGme7JsuMWVCeAJAKJQ
成功
{"errcode":0,"errmsg":"ok"}

效果:

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章