1. 程式人生 > >微信開發系列(六)_js呼叫微信掃碼

微信開發系列(六)_js呼叫微信掃碼

package com.weixin.util;import java.io.IOException;import org.apache.http.HttpEntity;import org.apache.http.client.methods.CloseableHttpResponse;import org.apache.http.client.methods.HttpGet;import org.apache.http.impl.client.CloseableHttpClient;import org.apache.http.impl.client.HttpClients;import org.apache.http.util.EntityUtils;import com.alibaba.fastjson.JSON;import com.alibaba.fastjson.JSONObject;public class HttpUtil {    private static String access_Token = "";    /**     * get請求獲取網址     * @param url     * @param charset     * @return     */    public static String sendGet(String url,String charset){        CloseableHttpClient httpClient=HttpClients.createDefault();        HttpGet get=new HttpGet(url);        CloseableHttpResponse response = null;          String result=null;        try {            response=httpClient.execute(get);            HttpEntity entity=response.getEntity();            //System.out.println(entity.getContentType().getValue());            result=EntityUtils.toString(entity,charset);        } catch (IOException e) {            // TODO Auto-generated catch block            e.printStackTrace();        }        return result;    }    //獲取tickect    public static String getJsTicket(){        JSONObject jsonObject = new JSONObject();        String ticket = "";        if(access_Token ==""){//如果是第一次獲取就直接去請求新的            ticket = getTicket();        }else{//否則就請求舊的            jsonObject = JSON.parseObject(result);            String resultCode = jsonObject.getString("errcode");            if(resultCode !="0"){//請求舊的如果不行                ticket = getTicket();//再去請求新的            }            else{//如果請求的新的ok                ticket = jsonObject.getString("ticket");//直接獲取            }        }        return ticket;    }    /**     * 獲取最新的ticket     * @return     */    public static String getTicket(){        JSONObject jsonObject = new JSONObject();        access_Token = WX_Token.getAccessTokenByNet().getAccess_token();//獲取Access_token程式碼就不貼了        String result = sendGet("https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token="+WX_Token.getAccessTokenByNet().getAccess_token()+"&type=jsapi","UTF-8");        jsonObject = JSON.parseObject(result);        return jsonObject.getString("ticket");    }}