我无法从Twitter API获得回复。我在这里使用scribe 1.3.5。当从一个页面调用TwitterLoginServlet时,它成功地将我重定向到twitter并允许我登录。但是,在回调中,TwitterCallbackServlet在oAuthResponse中收到以下信息。
代码 - 401 消息 - 未经授权 body - 无法验证oauth签名和令牌
我是使用servlet和oauth的新手,所以我完全有可能在下面的代码中犯了一些愚蠢的错误。我相信这是找到问题解决方案所需的全部内容,但如果您需要其他信息,我会警惕地查看这篇文章。
谢谢!
public class TwitterServlet extends HttpServlet {
private static final String SESSION_NAME_REQUEST_TOKN = "twitter.requestToken";
protected Token getRequestToken(HttpServletRequest req) {
HttpSession session = req.getSession();
try {
return (Token) session.getAttribute(SESSION_NAME_REQUEST_TOKN);
}
finally {
session.removeAttribute(SESSION_NAME_REQUEST_TOKN);
}
}
protected void setRequestToken(HttpServletRequest req, Token token) {
HttpSession session = req.getSession();
session.setAttribute(SESSION_NAME_REQUEST_TOKN, token);
}
protected OAuthRequest createRequest() {
OAuthRequest request = new OAuthRequest(Verb.GET, "https://api.twitter.com/oauth/request_token");
return request;
}
}
public class TwitterLoginServlet extends TwitterServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String callback = "http://" + request.getServerName() + ":" + request.getServerPort() + "/******/TwitterCallbackServlet";
OAuthService service = new ServiceBuilder().provider(TwitterApi.SSL.class)
.apiKey("******")
.apiSecret("******")
.callback(callback)
.build();
Token requestToken = service.getRequestToken();
setRequestToken(request, requestToken);
response.sendRedirect(service.getAuthorizationUrl(requestToken));
return;
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
public class TwitterCallbackServlet extends TwitterServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
OAuthService service = new ServiceBuilder().provider(TwitterApi.SSL.class)
.apiKey("******")
.apiSecret("******")
.build();
Token requestToken = getRequestToken(request);
// TODO: Check if the requestToken matches the token of this request.
String verifier = request.getParameter(OAuthConstants.VERIFIER);
Token accessToken = service.getAccessToken(requestToken, new Verifier(verifier));
OAuthRequest oAuthRequest = createRequest();
service.signRequest(accessToken, oAuthRequest);
Response oAuthResponse = oAuthRequest.send();
String body = oAuthResponse.getBody();
response.sendRedirect("/******/accountSettings.xhtml");
}
答案 0 :(得分:0)
为什么在获取访问令牌后再次访问requestToken
端点?尝试访问其他资源,例如:
"https://api.twitter.com/1.1/account/verify_credentials.json";
请注意,您可以运行TwitterExample只是为了检查内容是否正常。