Android:SNS客户端开发二:获取授权账号资料
在上一篇文章中,大致介绍了基于新浪微博开放平台的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.ou
补充:移动开发 , Android ,