Android:SNS客戶端開發二:獲取授權賬號資料 – Android移動開發技術文章_手機開發 Android移動開發教學課程

 

在上一篇文章中,大致介紹瞭基於新浪微博開放平臺的OAuth認證方法及相關實現。那麼在用戶成功授權,取到相應的AccessToken以及Access_secret後,我們就可以利用這兩個值通過新浪提供的對應API,去獲取用戶資料瞭。

 

     這裡我們需要用到Http請求相關的內容。獲取用戶資料是采用的Get方法,此處隻放出Get方法的相應代碼。使用HttpClient開源項目,該項目已經被Android包含無需單獨引入jar包。

 

    在獲取用戶資料時。通過Get方法傳遞的單數都要統一經過UTF-8編碼,並且與OAuth認證相關的參數一起簽名後再發送到服務器。廢話不多說,先看Get方法的代碼。

 

Java代碼 

public class WeiBoClient {  

    private OAuthConsumer consumer;  

    public WeiBoClient() {  

 

    }  

    public WeiBoClient(String consumerKey, String consumerSecret,  

            String oauthToken, String oauthTokenSecret) {  

        // 生成一個OAuthConsumer對象  

        consumer = new CommonsHttpOAuthConsumer(consumerKey, consumerSecret);  

        // 設置OAuth_Token和OAuth_Token_Secret  

        consumer.setTokenWithSecret(oauthToken, oauthTokenSecret);    

    }  

 

    public String doGet(String url, List<NameValuePair> addtionalParams) throws ClientProtocolException, IOException, OAuthMessageSignerException, OAuthExpectationFailedException, OAuthCommunicationException {  

        String result = null;  

        url = buildUrlByQueryAndBaseUrl(url, addtionalParams);  

        String signedUrl = null;  

          

            System.out.println("簽名之前的URL—>" + url);  

            signedUrl = consumer.sign(url);  

            System.out.println("簽名之後的URL—>" + signedUrl);  

          

        HttpGet getRequest = new HttpGet(signedUrl);  

        HttpClient httpClient = new DefaultHttpClient();  

        HttpResponse response = null;  

          

            response = httpClient.execute(getRequest);  

          

        result = parseStringFromEntity(response.getEntity());  

        return result;  

    }  

public String buildUrlByQueryAndBaseUrl(String url,List<NameValuePair> pairs){  

      String queryStr = URLEncodedUtils.format(pairs, "UTF-8");  

      return url + "?" + queryStr;  

}  

public String parseStringFromEntity(HttpEntity entity){  

String result = null;  

        try {  

            InputStream input = entity.getContent();  

            BufferedReader reader = new BufferedReader(new InputStreamReader(  

                    input));  

            String line = null;  

            StringBuffer sb = new StringBuffer();  

            while ((line = reader.readLine()) != null) {  

                sb.append(line);  

            }  

            result = sb.toString();  

        } catch (Exception e) {  

            System.out.println(e);  

        }  

        return result;  

}  

 

public class WeiBoClient {

       private OAuthConsumer consumer;

       public WeiBoClient() {

 

       }

       public WeiBoClient(String consumerKey, String consumerSecret,

                     String oauthToken, String oauthTokenSecret) {

              // 生成一個OAuthConsumer對象

              consumer = new CommonsHttpOAuthConsumer(consumerKey, consumerSecret);

              // 設置OAuth_Token和OAuth_Token_Secret

              consumer.setTokenWithSecret(oauthToken, oauthTokenSecret);

       }

 

       public String doGet(String url, List<NameValuePair> addtionalParams) throws ClientProtocolException, IOException, OAuthMessageSignerException, OAuthExpectationFailedException, OAuthCommunicationException {

              String result = null;

              url = buildUrlByQueryAndBaseUrl(url, addtionalParams);

              String signedUrl = null;

             

                     System.out.println("簽名之前的URL—>" + url);

                     signedUrl = consumer.sign(url);

                     System.out.println("簽名之後的URL—>" + signedUrl);

             

              HttpGet getRequest = new HttpGet(signedUrl);

              HttpClient httpClient = new DefaultHttpClient();

              HttpResponse response = null;

             

                     response = httpClient.execute(getRequest);

             

              result = parseStringFromEntity(response.getEntity());

              return result;

       }

public String buildUrlByQueryAndBaseUrl(String url,List<NameValuePair> pairs){

      String queryStr = URLEncodedUtils.format(pairs, "UTF-8");

      return url + "?" + queryStr;

}

public String parseStringFromEntity(HttpEntity entity){

String result = null;

              try {

                     InputStream input = entity.getContent();

                     BufferedReader reader = new BufferedReader(new InputStreamReader(

                                   input));

                     String line = null;

                     StringBuffer sb = new StringBuffer();

                     while ((line = reader.readLine()) != null) {

                            sb.append(line);

                     }

                     result = sb.toString();

              } catch (Exception e) {

                     System.out.println(e);

              }

              return result;

}

} 再在外部Activity中調用相應的方法就能獲取到賬號的資料瞭

 

Java代碼 

public void getUser(String access_token, String access_secret,  

            String user_id) throws ClientProtocolException, OAuthMessageSignerException, OAuthExpectationFailedException, OAuthCommunicationException, IOException {// 添加用戶  

                List<NameValuePair> params = new ArrayList<NameValuePair>();  

        BasicNameValuePair user_id = new BasicNameValuePair("user_id", user_id);  

        params.add(user_id);  

        WeiBoClient weibo = new WeiBoClient(SinaConstant.CONSUMER_KEY,SinaConstant.CONSUMER_SECRET, access_token, access_secret);  

        keyValues.put("user_id", user_id);  

        String userInfo;  

          

            userInfo = weibo.doGet(  

                    "https://api.t.sina.com.cn/users/show.json", params);   

          

        System.out.println(userInfo);  

        JSONObject user = null;  

        try {//對獲取到資料信息進行JSON解析  

            user = new JSONObject(userInfo);  

            String headUrl = user.getString("profile_image_url");  

            System.out.println(headUrl);  

 

            String screen_name = user.getString("screen_name");  

            String name = user.getString("name");  

            System.out.println(screen_name + "&&&" + name);  

 

              

        } catch (Exception e) {  

            e.printStackTrace();  

        }  

        // return null;  

            } 

 

public void getUser(String access_token, String access_secret,

                     String user_id) throws ClientProtocolException, OAuthMessageSignerException, OAuthExpectationFailedException, OAuthCommunicationException, IOException {// 添加用戶

                            List<NameValuePair> params = new ArrayList<NameValuePair>();

              BasicNameValuePair user_id = new BasicNameValuePair("user_id", user_id);

              params.add(user_id);

              WeiBoClient weibo = new WeiBoClient(SinaConstant.CONSUMER_KEY,SinaConstant.CONSUMER_SECRET, access_token, access_secret);

              keyValues.put("user_id", user_id);

              String userInfo;

             

                     userInfo = weibo.doGet(

                                   "https://api.t.sina.com.cn/users/show.json", params);

             

              System.out.println(userInfo);

              JSONObject user = null;

              try {//對獲取到資料信息進行JSON解析

                     user = new JSONObject(userInfo);

                     String headUrl = user.getString("profile_image_url");

                     System.out.println(headUrl);

 

                     String screen_name = user.getString("screen_name");

                     String name = user.getString("name");

                     System.out.println(screen_name + "&&&" + name);

 

                    

              } catch (Exception e) {

                     e.printStackTrace();

              }

              // return null;

                     } 以上代碼中的user_id為上一篇文章中我們獲取到的對應的用戶id。傳入參數請參考新浪微博開放平臺的API文檔,地址如下:https://open.weibo.com/wiki/Users/show

 

 

 

註:我這裡對所有方法的異常處理均為拋出,直到最頂層調用該方法時再捕捉,是為瞭再程序實現過程中對異常進行統一管理,同時也盡量規避因為提前捕捉而導致的程序崩潰。今天的代碼也均是如此

 

作者 river418

發佈留言