Android: SNS client development 2: Getting authorized account information

Source: Internet
Author: User
Tags oauth

 

In the previous article, we introduced the OAuth authentication method and related implementation based on the Sina Weibo open platform. After the user has successfully authorized and obtained the corresponding AccessToken and Access_secret, we can use these two values to obtain the user information through the corresponding API provided by Sina.

 

Here we need to use Http request-related content. The Get method is used to obtain user data. Here, only the corresponding code of the Get method is released. Using the HttpClient open-source project, this project has been included by Android without the need to introduce the jar package separately.

 

When obtaining user information. The singular numbers passed through the Get method must all be encoded by the UTF-8 and signed together with the parameters related to OAuth authentication before being sent to the server. Let's talk about the Get method code first.

 

Java code

Public class WeiBoClient {

Private OAuthConsumer consumer;

Public WeiBoClient (){

 

}

Public WeiBoClient (String consumerKey, String consumerSecret,

String oauthToken, String oauthTokenSecret ){

// Generate an OAuthConsumer object

Consumer = new CommonsHttpOAuthConsumer (consumerKey, consumerSecret );

// Set OAuth_Token and 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 before signature --->" + url );

SignedUrl = consumer. sign (url );

System. out. println ("signed URL --->" + signedUrl );

HttpGet getRequest = new HttpGet (signedUrl );

HttpClient httpClient = new DefaultHttpClient ();

HttpResponse response = null;

Response = httpClient.exe cute (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 ){

// Generate an OAuthConsumer object

Consumer = new CommonsHttpOAuthConsumer (consumerKey, consumerSecret );

// Set OAuth_Token and 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 before signature --->" + url );

SignedUrl = consumer. sign (url );

System. out. println ("signed URL --->" + signedUrl );

HttpGet getRequest = new HttpGet (signedUrl );

HttpClient httpClient = new DefaultHttpClient ();

HttpResponse response = null;

Response = httpClient.exe cute (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;

}

} Then, call the corresponding method in the external Activity to obtain the account information.

 

Java code

Public void getUser (String access_token, String access_secret,

String user_id) throws ClientProtocolException, OAuthMessageSignerException, OAuthExpectationFailedException, OAuthCommunicationException, IOException {// Add a user

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 (

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

System. out. println (userInfo );

JSONObject user = null;

Try {// parse the obtained information in JSON format

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 {// Add a user

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 (

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

System. out. println (userInfo );

JSONObject user = null;

Try {// parse the obtained information in JSON format

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;

} The user_id in the above Code is the user ID we obtained in the previous article. For the input parameters, see the Sina Weibo open platform API documentation, address: http://open.weibo.com/wiki/Users/show

 

 

 

Note: I will throw the Exception Handling for all methods until the top-level method is called to capture the exception, in order to manage the exception in a unified way during program implementation, at the same time, we also try to avoid program crashes caused by early capturing. This is also true for today's code.

 

Author river418

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.