网站使用新浪微博登录

       
       主要涉及到了oauth2.0的概念,这个网上资料有很多,大家可以google一下。

         首先去新浪sae申请了一个服务器,创建了一个应用: http://1.xxx.sinaapp.com/xxx.jsp然后去新浪微博开发平台申请成为开发者。在管理中心添加一个网站进行验证,如下图所示。网站名称:lijiejava软件开发,网站域名就是sae中的应用。

         验证之后可以获得App key ,App Sercet 。有个这2个东西,就可以开始coding了。

         第1步:点击登录按钮,跳转到新浪微博提供的登录、授权页面。URL是:
"https://api.weibo.com/oauth2/authorize?client_id="+appKey+"&response_type=code&redirect_uri="+redirectURL;

String redirectURL = "http://1.lijiecode.sinaapp.com/weibo/login";


主要参数:client_id 以及 redirect_uri 。client_id 及App Key值,redirect_uri(回调接口),用于验证成功之后,新浪微博的回调。这里的redirect_uri与client_id必须对应,就是redirect_uri需要是你在网站验证时输入的域名,否则会出现如下错误:



用户在该页面输入新浪微博的用户名、密码,并同意授权,新浪微博server便会回调redirect_uri接口,并返回一个code值。



第2步:在回调接口中获得新浪微博server返回的code值,根据这个code值就可以获取accestoken以及用户在微博中的uid 。


String url = "https://api.weibo.com/oauth2/access_token";
	    Map<String,String> postData = new HashMap<String,String>();
	    postData.put("grant_type", "authorization_code");
	    postData.put("code", code);
	    postData.put("redirect_uri", redirectURL);
	    postData.put("client_id", appKey);
	    postData.put("client_secret", appSercet);
返回的数据中包含access_token 以及uid数据。

获得access_token以及uid之后,就可以通过下面的url去获取用户在新浪微博中的各种数据了,包括用户名,位置,描述,头像等等。

部署的时候遇到2个问题:

1.由于我这个网站只是验证,没有审核,所以必须是我在后台添加的测试用户才能正确获取信息,否则会出现如下错误。没有添加的用户,即使输入正确的用户名、密码也无法获得信息。
{"error":
"applications over the unaudited use restrictions!",
"error_code":21321,"request":"/2/users/show.json"}  



2. 新浪sae中不支持HttpClient ,需要使用其提供的SaeFetchurl 类。

猜你喜欢

转载自lijiejava.iteye.com/blog/2086030