---
title: "Android：SNS客户端开发二：获取授权账号资料"
author: "river418"
date: "2011-12-05T15:09:05Z"
tags: []
categories: ["移动开发"]
slug: "android-sns"
draft: false
lastmod: "2011-12-05T21:39:39Z"
id: 1292209
url: "https://river418.iteye.com/blog/1292209"
---

在上一篇文章中，大致介绍了基于新浪微博开放平台的OAuth认证方法及相关实现。那么在用户成功授权，取到相应的AccessToken以及Access\_secret后，我们就可以利用这两个值通过新浪提供的对应API，去获取用户资料了。

     这里我们需要用到Http请求相关的内容。获取用户资料是采用的Get方法，此处只放出Get方法的相应代码。使用HttpClient开源项目，该项目已经被Android包含无需单独引入jar包。

    在获取用户资料时。通过Get方法传递的单数都要统一经过UTF-8编码，并且与OAuth认证相关的参数一起签名后再发送到服务器。废话不多说，先看Get方法的代码。

```
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中调用相应的方法就能获取到账号的资料了

```
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(
					"http://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文档，地址如下：[http://open.weibo.com/wiki/Users/show](http://open.weibo.com/wiki/Users/show)

 

注:我这里对所有方法的异常处理均为抛出，直到最顶层调用该方法时再捕捉