微信公衆平臺網頁授權獲取openid代碼

		String code = get("code");		
		 //創建httpClient請求
        CloseableHttpClient httpClient = HttpClients.createDefault();
        //請求地址
        String url = "https://api.weixin.qq.com/sns/oauth2/access_token";
        //創建httpPost
        HttpPost httpPost = new HttpPost(url);
        //創建 參數集合
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        //添加參數
        params.add(new BasicNameValuePair("appid" , Tools.appId));
        params.add(new BasicNameValuePair("secret" , Tools.appSecret));
        params.add(new BasicNameValuePair("code" , code));
        params.add(new BasicNameValuePair("grant_type" , "authorization_code"));

        //將參數集合添加到httpPost
        try {
			httpPost.setEntity(new UrlEncodedFormEntity(params));
		} catch (UnsupportedEncodingException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}

        httpPost.setHeader("Content-Type", "application/json;charset=UTF-8");

        // 響應
        CloseableHttpResponse resp = null;
        try {
            // 由客戶端執行(發送)Post請求
            resp = httpClient.execute(httpPost);

            // 從響應模型中獲取響應實體
            HttpEntity responseEntity = resp.getEntity();

            //System.out.println("響應狀態爲:" + resp.getStatusLine());
            if (responseEntity != null) {
                //System.out.println("響應內容長度爲:" + responseEntity.getContentLength());
            	String content = EntityUtils.toString(responseEntity);            	
            	JSONObject obj = JSON.parseObject(content);
            	System.out.println("open_id=" + obj.get("openid"));
               // System.out.println("響應內容爲:" + EntityUtils.toString(responseEntity));
                
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (ParseException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                // 釋放資源
                if (httpClient != null) {
                    httpClient.close();
                }
                if (resp != null) {
                    resp.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }     
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章