在上一篇內容已經介紹了怎么申請twitter開放的API接口。
下面介紹怎么通過twitter提供的API,進行授權登錄功能。
開發(fā)者頁面設置
首先在開發(fā)者頁面開啟“用戶認證設置”,點擊edit進行信息編輯。
我的授權登錄是個網頁,并且只需要進行簡單的登錄和獲取登錄人員基礎信息這些信息,所以進行了以下設置。
這里一定要配置回調地址,這個地址至關重要。
測試期間不需要域名這些,也不需要天公網IP。
內網本地地址就可以,http://localhost:63342/index.html 也可以(自己可以寫一個簡單的測試頁)
了解授權步驟
編寫代碼之前我們要先了解twitter授權登錄的三步驟。
https://developer.twitter.com/en/docs/authentication/guides/log-in-with-twitter
以上鏈接有詳細的授權驗證過程,當然我也可以簡單介紹一下。
- 請求https://api.twitter.com/oauth/request_token接口。 在請求這個接口的時候,不僅要傳申請的consumerKey和consumerSecret,還得填寫oauth_callback的值。這個值的內容填寫你上面在Callback URL里填寫的回調地址【http://localhost:63342/index.html】。
- 請求成功后拿到oauth_token值,網頁調轉到https://api.twitter.com/oauth/authenticate頁面,鏈接后面加上 ** ?oauth_token= ** 的值。
參數(shù)成功的話,會正確調轉到twitter授權的頁面,點擊授權按鈕后,twitter頁面會跳轉回你填寫的頁面鏈接。
回到自己的頁面后,頁面的URL會攜帶兩個參數(shù)和參數(shù)值。oauth_token和oauth_verifier
- 拿到URL中傳回的這兩個值,請求https://api.twitter.com/oauth/access_token接口,拿到用戶授權的screen_name和user_id,auth_token和oauth_token_secret這些值。
- token和token_secret兩個參數(shù),可以通過請求https://api.twitter.com/2/users/me接口獲取用戶的一些基礎信息。
注意!以上過程,oauth_token和oauth_verifier的值失效時間很短暫,找到一個帖子說只有30秒,所以接口連貫性請求很重要,只有速度,快速授權過程才能完成。
編寫代碼
流程介紹完,開始編寫代碼。
- 首先,網頁上增加一個按鈕。
<!-- 點擊按鈕觸發(fā)授權 -->
<button onclick="authorizeTwitter()">Twitter授權登錄</button>
編寫js代碼,authorizeTwitter()方法
function authorizeTwitter() {
// 發(fā)起授權請求
$.ajax({
url:'http://localhost:8070/twitter/login',
type:'POST',
async: true,
cache: false,
contentType: false, //不設置內容類型
processData: false, //不處理數(shù)據(jù)
success:function(data){
var code = data.code;
if(code == 200){
window.location.href ="https://api.twitter.com/oauth/authenticate?oauth_token="+data.result;
}else{
console.error('授權請求錯誤:');
layer.alert("請求失敗,請稍候重試");
}
}
});
}
- twitter/login接口核心代碼如下
callback的傳值就是開發(fā)者里配置的Callback URL的填寫的值。
和網頁配置的保持一致,不可隨意傳值。
active的值只是用于開啟代理的開關,上篇代碼有寫,根據(jù)自己需求傳不同的值。
/**
* 第一步:通過授權code獲取token
* @param active 當前環(huán)境 dev test prod
* @return
*/
public static String RequestToken(String callback,String active) {
CommonsHttpOAuthConsumer consumer = new CommonsHttpOAuthConsumer(consumerKey, consumerSecret);
// 創(chuàng)建HttpParameters對象,并添加自定義參數(shù)
HttpParameters parameters = new HttpParameters();
parameters.put(OAuth.OAUTH_CALLBACK, callback);
consumer.setAdditionalParameters(parameters);
// 創(chuàng)建HttpClient對象
HttpClient httpClient = setProxy(active);
// 創(chuàng)建API請求,例如獲取用戶的時間線
String apiUrl = "https://api.twitter.com/oauth/request_token";
HttpGet request = new HttpGet(apiUrl);
// 對請求進行OAuth1簽名
try {
consumer.sign(request);
} catch (OAuthMessageSignerException e) {
e.printStackTrace();
} catch (OAuthExpectationFailedException e) {
e.printStackTrace();
} catch (OAuthCommunicationException e) {
e.printStackTrace();
}
// 發(fā)起API請求
HttpResponse response = null;
try {
response = httpClient.execute(request);
} catch (IOException e) {
e.printStackTrace();
}
// 處理API響應
int statusCode = response.getStatusLine().getStatusCode();
String responseBody = null;
try {
responseBody = EntityUtils.toString(response.getEntity());
} catch (IOException e) {
e.printStackTrace();
}
if (statusCode == 200) {
System.out.println("API調用成功!");
System.out.println("響應內容:");
System.out.println(responseBody);
return responseBody;
} else {
System.out.println("API調用失敗,狀態(tài)碼:" + statusCode);
System.out.println("錯誤信息:");
System.out.println(responseBody);
return responseBody;
}
}
成功返回的值形式如下:
oauth_token=qQn3YwAAAAABq1bmAAABi9gPG1M&oauth_token_secret=2QBmMyDV450YG1dtdf5KnnGrztnRXKmR&oauth_callback_confirmed=true
我用httpcore工具進行解析,需要用到的類如下。
import org.apache.http.NameValuePair;
import org.apache.http.client.utils.URLEncodedUtils;
List<NameValuePair> parameters = URLEncodedUtils.parse(responseString, StandardCharsets.UTF_8);
// 遍歷參數(shù)并輸出鍵值對
for (NameValuePair parameter : parameters) {
String key = parameter.getName();
String value = parameter.getValue();
map.put(key,value);
}
把oauth_token值傳到前臺頁面,前臺頁面進行跳轉。
參考如下:
https://api.twitter.com/oauth/authenticate?oauth_token=qQn3YwAAAAABq1bmAAABi9gPG1M
授權成功之后,調轉回調頁面。如果之前授權過,會很快跳轉到回調頁面。
http://localhost:63342/index.html?oauth_token=s19K7gAAAAABq1bmAAABi9fpDPI&oauth_verifier=cHqqlM9vi0gn8EDDtrCmUvh3jCSQCGcL
拿到oauth_token和oauth_verifier的值,頁面load()方法解析獲取oauth_token和oauth_verifier請求第二個接口。
function callbackTwitter(token,verifier) {
var authorize = new FormData();
authorize.append("oauth_token",token);
authorize.append("oauth_verifier",verifier);
console.log(authorize);
// 發(fā)起授權請求
$.ajax({
url:'http://localhost:8070/twitter/verifier',
type:'POST',
data:authorize,
async: true,
cache: false,
contentType: false, //不設置內容類型
processData: false, //不處理數(shù)據(jù)
success:function(data){
// var data = eval('(' + data + ')');
var code = data.code;
if(code == 200){
//自己業(yè)務
}else{
console.error('授權請求錯誤:');
layer.alert("請求失敗,請稍候重試");
}
}
});
}
第二個接口核心Java代碼。
oauth_verifier值是放在請求體里,和第一個接口oauth_callback參數(shù)方式有些不同。
/**
* 第二部,頁面跳轉
* @param token
* @param verifier
* @param active
* @return
*/
public static String callback(String token,String verifier, String active) {
// 創(chuàng)建CommonsHttpOAuthConsumer對象,設置OAuth1驗證參數(shù)
CommonsHttpOAuthConsumer consumer = new CommonsHttpOAuthConsumer(consumerKey, consumerSecret);
// 創(chuàng)建HttpParameters對象,并添加自定義參數(shù)
HttpParameters parameters = new HttpParameters();
parameters.put(OAuth.OAUTH_TOKEN, token);
consumer.setAdditionalParameters(parameters);
// 創(chuàng)建HttpClient對象
HttpClient httpClient = setProxy(active);
// 創(chuàng)建API請求,例如獲取用戶的時間線
String apiUrl = "https://api.twitter.com/oauth/access_token";
HttpPost request = new HttpPost(apiUrl);
try {
request.setHeader("Content-Type","application/x-www-form-urlencoded");
consumer.sign(request);
// 創(chuàng)建參數(shù)列表
List<NameValuePair> bodypara = new ArrayList<>();
bodypara.add(new BasicNameValuePair("oauth_verifier", verifier));
// 將參數(shù)轉換為UrlEncodedFormEntity
StringEntity entity = new UrlEncodedFormEntity(bodypara, StandardCharsets.UTF_8);
// 設置HttpPost的實體
request.setEntity(entity);
// request.setEntity();
} catch (OAuthMessageSignerException e) {
e.printStackTrace();
} catch (OAuthExpectationFailedException e) {
e.printStackTrace();
} catch (OAuthCommunicationException e) {
e.printStackTrace();
}
// 發(fā)起API請求
HttpResponse response = null;
try {
response = httpClient.execute(request);
} catch (IOException e) {
e.printStackTrace();
}
// 處理API響應
int statusCode = response.getStatusLine().getStatusCode();
String responseBody = null;
try {
responseBody = EntityUtils.toString(response.getEntity());
} catch (IOException e) {
e.printStackTrace();
}
if (statusCode == 200) {
System.out.println("API調用成功!");
System.out.println(responseBody);
return responseBody;
} else {
System.out.println("API調用失敗,狀態(tài)碼:" + statusCode);
return responseBody;
}
}
請求成功后的返回內容。
oauth_token=1517001992861716480-xVY7MpIqQrH1XeFv5l6rOL0FqG9WPj&oauth_token_secret=A52yWlrFd1MDIrYU0IcnmlnmimMOw0UXRJNfnry3bJNfm&user_id=151700199286171xxxx&screen_name=TTTTTTTXX
這用戶的重要的用戶ID和用戶名就獲取到了。
整個授權流程算是完成了。文章來源:http://www.zghlxwxcb.cn/news/detail-758448.html
我的業(yè)務是需要獲取用戶的粉絲數(shù)和其他一些基礎信息,這時候就可以用返回的oauth_token和oauth_token_secret兩個值請求https://api.twitter.com/2/users/me接口。
代碼示例可在上篇看到。文章來源地址http://www.zghlxwxcb.cn/news/detail-758448.html
到了這里,關于java代碼編寫twitter授權登錄的文章就介紹完了。如果您還想了解更多內容,請在右上角搜索TOY模板網以前的文章或繼續(xù)瀏覽下面的相關文章,希望大家以后多多支持TOY模板網!