解決微信公眾號accessToken白名單問題


獲取微信公眾號accessToken需要服務器ip配置白名單,但部分客戶服務器沒有固定ip,因而經常會出現因為ip白名單問題而獲取不到公眾號的accessToken。

解決辦法:proxy代理

public String sendGet(String url, String param) {
        String result = "";
        BufferedReader in = null;
        try {
            String urlNameString = url + "?" + param;

            URL realUrl = new URL(urlNameString);

            //proxy代理服務
            String host = "www.baidu.com";//代理服務器域名
            String port = "8080";//端口號
            //InetAddress.getByName(host),通過域名獲得ip地址
            InetSocketAddress socketAddress = new InetSocketAddress(InetAddress.getByName(host), port);
            Proxy proxy = new Proxy(Proxy.Type.HTTP,socketAddress);
            
            // 打開和URL之間的連接
            URLConnection conn = realUrl.openConnection();
            if (proxy != null) {
                conn = realUrl.openConnection(proxy);
            }
            // 設置通用的請求屬性
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("Charset", "utf-8");
            conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            // 建立實際的連接
            conn.connect();

            // 獲取所有響應頭字段
            Map<String, List<String>> map = conn.getHeaderFields();
            /*
             * // 遍歷所有的響應頭字段 for (String key : map.keySet()) { log.debug(key +
             * "--->" + map.get(key)); }
             */
            // 定義 BufferedReader輸入流來讀取URL的響應
            // out = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");
            in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            log.debug("發送GET請求失敗:" + ExceptionHelper.GetErrInfo(e));
        }
        // 使用finally塊來關閉輸入流
        finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception e2) {
                log.info(e2.getMessage());
            }
        }
        return result;
    }

 

補充:

407 Proxy Authentication Required

與401響應類似,只不過客戶端必須在代理服務器上進行身份驗證。代理服務器必須返回一個 Proxy-Authenticate 用以進行身份詢問。客戶端可以返回一個 Proxy-Authorization 信息頭用以驗證。參見RFC 2617。
If your proxy requires authentication it will give you response 407.

In this case you'll need the following code:

    Authenticator authenticator = new Authenticator() {

        public PasswordAuthentication getPasswordAuthentication() {
            return (new PasswordAuthentication("user",
                    "password".toCharArray()));
        }
    };
    Authenticator.setDefault(authenticator);

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM