java實現新浪oauth2.0獲取用戶信息並發表一條微博

剛剛工做.......... 工做中用到了新浪微博的oauth , 由於用到的功能很少,並無用新浪的SDK,都是本身寫的,沒有考慮大多數的異常處理。 oauth驗證過程再也不敘述。 用到了struts2。java

引導用戶到受權界面當用戶在網站上點擊用新浪微博登錄後的執行過程。json

<!-- lang: java -->
 public String authWeiboSignIn()
{
	authorizationURL = "https://api.weibo.com/oauth2/authorize?client_id="+appKEY+"&response_type=code&redirect_uri=callbackURL";
	return SUCCESS;
}

struts2的xml配置api

<!-- lang: java -->
<action name="weiboSinaSignIn" class="com.tech.action.SinaAction"
		method="authWeiboSignIn">
		<result name="success" type="redirect">${authorizationURL}</result>
</action>

用戶受權完成後會返回code,這個code是之後全部操做的鑰匙,經過code能夠得到accessToken和uid ,uid和accessToken就是訪問新浪API的憑證。 用戶贊成受權後,根據redirect_uri能夠從新返回。我在redirect_uri中配置了要請求的action,流程就轉到了action所配置的方法。 redirect_uri返回的action配置app

<!-- lang: java -->
<action name="weiboLogin" class="com.tech.action.SinaAction"
		method="weiboLogin">
<action/>

方法中獲取請求後的code,讓後用http post請求獲取accessToken和uidpost

<!-- lang: java -->
public String weiboLogin() {
	HttpServletRequest request = ServletActionContext.getRequest();
	String code = request.getParameter("code");
	Map<String, String> token = this.getAccessTokenAndUid(code);
}
/**
 * 獲取accestoken和用戶在新浪微博的uid
 * @param code 獲取accessToken的鑰匙
 * @return
 */
private Map<String , String> getAccessTokenAndUid(String code){
	String responseDate = "" ;
	Map<String , String> token = new HashMap<String, String>();
            //本機運行時會報證書錯誤
	/*ProtocolSocketFactory fcty = new MySecureProtocolSocketFactory();
	Protocol.registerProtocol("https", new Protocol("https", fcty, 443));*/
	PostMethod postMethod = new PostMethod("https://api.weibo.com/oauth2/access_token");
	postMethod.addParameter("grant_type", "authorization_code");
	postMethod.addParameter("code",code);
	postMethod.addParameter("redirect_uri","callBackURL");
	postMethod.addParameter("client_id",KEY);
	postMethod.addParameter("client_secret",appSECRET);
	HttpClient client = new HttpClient();
	try {
		client.executeMethod(postMethod);
		responseDate = postMethod.getResponseBodyAsString();
	} catch (Exception e) {
		e.printStackTrace();
	}
	if(!responseDate.equals("") && responseDate.indexOf("access_token") != -1){
		JSONObject jsonData = JSONObject.fromObject(responseDate);
		token.put("accessToken", (String)jsonData.get("access_token"));
		token.put("uid", jsonData.getString("uid"));
	}
	return	token;
}

如今的map結合中存儲了accessToken和uid , 就能取得受權用戶的信息了。這裏我只須要微博名稱和用戶的頭像地址。網站

<!-- lang: java -->
public String weiboLogin() {
	HttpServletRequest request = ServletActionContext.getRequest();
	String code = request.getParameter("code");
	Map<String, String> token = this.getAccessTokenAndUid(code);
	Map<String , String> userInfo = this.getUserWeiBoInfo(token);
}


private Map<String , String> getUserWeiBoInfo(Map<String , String> token){
	Map<String , String> userData = new HashMap<String, String>();
	String UserInfo = "";
	String url = "https://api.weibo.com/2/users/show.json?access_token="+token.get("sinaUid")"&uid="+token.get("sinaAccessToken");
	GetMethod getMethod = new GetMethod(url);
	HttpClient client = new HttpClient();
	try {
		client.executeMethod(getMethod);
		UserInfo = getMethod.getResponseBodyAsString();
		JSONObject jsonData = JSONObject.fromObject(UserInfo);
		userData.put("name",jsonData.getString("name").toString() );
		userData.put("headImg", jsonData.getString("profile_image_url"));
	} catch (Exception e) {
		e.printStackTrace();
	}
	return userData;
}

在受權用戶中發表一篇微博:ui

<!-- lang: java -->
public String weiboLogin() {
	HttpServletRequest request = ServletActionContext.getRequest();
	String code = request.getParameter("code");
	Map<String, String> token = this.getAccessTokenAndUid(code);
	Map<String , String> userInfo = this.getUserWeiBoInfo(token);
	this.shareToSina(token);
}
private void shareToSina(Map<String , String>) throws IllegalArgumentException, HttpException, IOException
{
	/*ProtocolSocketFactory fcty = new MySecureProtocolSocketFactory();
	Protocol.registerProtocol("https", new Protocol("https", fcty, 443));*/
	PostMethod postMethod = new PostMethod("https://api.weibo.com/2/statuses/update.json");
	postMethod.addParameter("access_token", token.get("sinaAccessToken"));
	postMethod.addParameter("status","發表一條微博");
	HttpMethodParams param = postMethod.getParams();
	param.setContentCharset("UTF-8");
	HttpClient client = new HttpClient();
	client.executeMethod(postMethod);
	postMethod.getResponseBodyAsString();
}
相關文章
相關標籤/搜索