OAuth2 Java - How to set the Accept header
I am trying to implement a "login with Github" functionality for my site using a hybrid solution - the javascript site does the initial login / credentials, and the redirect url is for tomcat servlets continuing to request access to the token.
I am using oauth2 library for google API for Java.
Currently my code looks like this:
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();
It doesn't work and I get the following exception:
com.fasterxml.jackson.core.JsonParseException: Unrecognized token 'access_token': was expecting ('true', 'false' or 'null')
I went through it and found an answer from Github not in json format (which JacksonFactory expects), but it actually looks like this:
access_token=xxxxxxxxxxx&scope=user%3Aemail&token_type=bearer
I found at https://developer.github.com/v3/media/#request-specific-version that I need to set the Accept http header for the request as application / vnd.github.v3 + json so that it will return something in json format.
How can I do this using google oauth2 api?
EDIT: Based on tinker's answer , I solved it with the following addition:
tokenRequest.setRequestInitializer(new HttpRequestInitializer()
{
@Override
public void initialize(HttpRequest request) throws IOException
{
request.getHeaders().setAccept("application/json");
}
});
source to share
You need to create an HttpRequest and add headers to it. Have a look at the javadoc for customizing request headers.
From AuthorizationCodeTokenRequest
you can get HttpRequestInitializer
using getRequestInitializer()
. If this value is null, you can create an initializer and use setRequestInitializer()
with the newly created object.
With the initializer, you can now initialize
request the header you want .
I haven't tested this, so I'm not entirely sure, but from the docs it looks like the only way to do it.
source to share