【发布时间】:2015-06-23 13:52:42
【问题描述】:
我正在尝试使用混合解决方案为我的网站实现“使用 Github 登录”功能 - 该网站的 javascript 执行初始登录/凭据,重定向 url 用于继续访问令牌请求的 tomcat servlet。
我正在使用适用于 Java 的 Google API oauth2 库。
我的代码目前如下所示:
AuthorizationCodeTokenRequest tokenRequest =
new AuthorizationCodeTokenRequest(
new NetHttpTransport(),
new JacksonFactory(),
new GenericUrl("https://github.com/login/oauth/access_token"),
code)
.setClientAuthentication(
new ClientParametersAuthentication(
GITHUB_CLIENT_ID, GITHUB_CLIENT_SECRET));
TokenResponse tokenResponse = tokenRequest.execute();
这不起作用,我收到以下异常:
com.fasterxml.jackson.core.JsonParseException: Unrecognized token 'access_token': was expecting ('true', 'false' or 'null')
我查看了它,发现来自 Github 的响应不是 json 格式(JacksonFactory 期望的),但实际上看起来像这样:
access_token=xxxxxxxxxxx&scope=user%3Aemail&token_type=bearer
我在https://developer.github.com/v3/media/#request-specific-version 中发现我需要将请求的 Accept http 标头设置为 application/vnd.github.v3+json 以使其返回 json 格式的内容。
如何使用 Google 的 oauth2 api 做到这一点?
编辑: 根据tinker的回复,我解决了以下问题:
tokenRequest.setRequestInitializer(new HttpRequestInitializer()
{
@Override
public void initialize(HttpRequest request) throws IOException
{
request.getHeaders().setAccept("application/json");
}
});
【问题讨论】: