我在使用
Google OAuth Java Client调用twitter REST API时遇到问题.我能够正确地完成第一步:
>设置授权URL,
>获取临时令牌,
>生成最终令牌.
Use the stored access token to authorize HTTP requests to protected
resources by setting the OAuthParameters.token and using
OAuthParameters as the HttpRequestInitializer.
正是在这一步中,我遇到了问题.首先,如果我只设置OAuthParameters.token值,我将得到一个null异常,因为签名者没有设置,所以我现在拥有的是:
OAuthHmacSigner signer = new OAuthHmacSigner();
signer.clientSharedSecret=TWITTER_CONSUMER_SECRET;
String oauthToken = req.getParameter("oauth_token");
String oauthVerifier = req.getParameter("oauth_verifier");
OAuthGetAccessToken accessTokenRequest = new OAuthGetAccessToken(TWITTER_ACESS_TOKEN_URL);
accessTokenRequest.consumerKey=TWITTER_CONSUMER_KEY;
accessTokenRequest.signer=signer;
accessTokenRequest.transport=HTTP_TRANSPORT;
accessTokenRequest.temporaryToken=oauthToken;
accessTokenRequest.verifier=oauthVerifier;
OAuthCredentialsResponse credentials = accessTokenRequest.execute();
String token = credentials.token;
OAuthParameters params = new OAuthParameters();
params.token=token;
params.version="1.0";
params.consumerKey=TWITTER_CONSUMER_KEY;
params.signer=signer;
HttpRequestFactory requestFactory = HTTP_TRANSPORT.createRequestFactory(params);
HttpResponse twResponse = requestFactory.buildGetRequest(new GenericUrl("https://api.twitter.com/1.1/account/verify_credentials.json")).execute();
结果总是:
WARNING: Authentication error: Unable to respond to any of these
challenges: {} com.google.api.client.http.HttpResponseException: 401
OK {“errors”:[{“message”:”Could not authenticate you”,”code”:32}]}
如果我尝试使用Twitter OAuth工具通过REST Chrome扩展工具提供的授权标头,它可以完美运行,因此不存在帐户问题.当我为Google OAuth Java客户端库计算的Authorization标头值更改它时,它不起作用.
我不知道我做错了什么.
解决方案:按照@Arkanon提供的链接中的教程,我错过了刷新签名者令牌的方法:
signer.tokenSharedSecret
最佳答案 我刚刚修改了
this page about using google-oauth-java-client上的代码以向Twitter发送请求,一旦我用相应的块替换了它,它工作正常:
while (currentLine.equalsIgnoreCase("n")) {
System.out.println("Enter the verification PIN provided by Twitter:");
currentLine = in.readLine();
}
然后将以下内容添加到accessToken对象:
accessToken.verifier = currentLine;
将Twitter站点提供的PIN输入Java控制台并按Enter键后,该过程即可完成,并且可以访问受保护的资源并接收所需的JSON响应.
我对该代码所做的唯一其他更改是提供Twitter常量,如下所示:
private static final String CONSUMER_KEY =
"enter-your-consumer-key-here";
private static final String CONSUMER_SECRET =
"enter-your-consumer-secret-here";
private static final String PROTECTED_SERVICE_URL =
"https://api.twitter.com/1.1/statuses/home_timeline.json";
private static final String REQUEST_TOKEN_URL =
"https://api.twitter.com/oauth/request_token";
private static final String AUTHORIZE_URL =
"https://api.twitter.com/oauth/authenticate";
private static final String ACCESS_TOKEN_URL =
"https://api.twitter.com/oauth/access_token";
也许这不是您希望实现的完全相同的过程,但希望该页面上的代码可以帮助您发现您可能误解的任何内容. (我同意Google图书馆的文档并非完全可以.)