我试图掌握 Play 框架如何处理其 Web 服务调用。
这是 Foursquare 的方向(在 1 和 2 之后):
Your server will make a request for
https://foursquare.com/oauth2/access_token
?client_id=YOUR_CLIENT_ID
&client_secret=YOUR_CLIENT_SECRET
&grant_type=authorization_code
&redirect_uri=YOUR_REGISTERED_REDIRECT_URI
&code=CODE
The response will be JSON
{ access_token: ACCESS_TOKEN }
这是我的代码:
public static Result index() {
String base = "http://foursquare.com/oauth2/authenticate";
String clientId = "?client_id=***";
String responseType = "&response_type=code";
String redirectUri = "&redirect_uri=http://localhost:9000/code";
return redirect(base + clientId + responseType + redirectUri);
}
public static Result code() {
String base = "http://foursquare.com/oauth2/access_token";
String clientId = "?client_id=***";
String clientsecret = "&client_secret=***";
String grantType = "&grant_type=authorization_code";
String redirectUri = "&redirect_uri=http://localhost:9000/json";
String code = "&code=" + request().getQueryString("code");
return redirect(base + clientId + clientsecret + grantType
+ redirectUri + code);
}
有两件事我很好奇:
1)我被重定向到屏幕上显示访问令牌的页面:
网址:https://foursquare.com/oauth2/access_token?client_id=***&client_secret=***&grant_type=authorization_code&redirect_uri=http://localhost:9000/json&code=***
显示如下:
{"access_token":"***"}
我本来希望被重定向到,http://localhost:9000/json
因为那是重定向 uri ...
2) 如何获取访问令牌?我已经尝试使用异步 Web 服务调用访问 http://www.playframework.com/documentation/2.2.x/JavaWS但我无法让它们工作。
我的尝试:
String feedUrl = base + clientId + clientsecret + grantType
+ redirectUri + code;
final Promise<Result> resultPromise = WS.url(feedUrl).get().map(
new Function<WS.Response, Result>() {
public Result apply(WS.Response response) {
return ok("Feed title:" + response.asJson().findPath("access_token").asText());
}
}
);
return resultPromise;
这给了我一个例外:[ConnectException: Connection refused: no further information: foursquare.com/107.23.103.139:80 to http://foursquare.com/oauth2/access_token]
非常感谢所有帮助!