Reputation: 51
I'm developing GAE application that needs to send authorized shorten URL requests, so they show up in users http://goo.gl dashboard. I'm using Google URL shortener API for Java library (google-api-services-urlshortener-v1-rev12-1.12.0-beta.jar) following way:
public void doGet(HttpServletRequest req, HttpServletResponse resp)
throws IOException {
Urlshortener shortener = newUrlshortener();
Url toInsert = new Url().setLongUrl("http://www.google.com");
Url inserted = new Url();
try {
inserted = shortener.url().insert(toInsert).setOauthToken("{accessToken}").execute();
} catch (Exception e) {
resp.sendError(404, e.getMessage());
}
}
public static Urlshortener newUrlshortener() {
AppIdentityCredential credential =
new AppIdentityCredential(Arrays.asList(UrlshortenerScopes.URLSHORTENER));
return new Urlshortener.Builder(new UrlFetchTransport(), new JacksonFactory(), credential)
.build();
}
My request gets processed and I can retrieve short URL, but it does not show up in users http://goo.le dashboard.
I can do it using curl, and it works as it should. Request shows up in users dashboard:
curl https://www.googleapis.com/urlshortener/v1/url -H 'Content-Type: application/json' -H 'Authorization: Bearer {sameAccessToken}' -d '{"longUrl": "http://www.google.com/"}'
I have also tried adding Authorization HttpHeader to request but it didn't work:
HttpHeaders headers = new HttpHeaders();
headers.put("Authorization", "Bearer {sameAccessToken}");
inserted = shortener.url().insert(toInsert).setRequestHeaders(headers).execute();
Upvotes: 3
Views: 2343
Reputation: 51
I was doing it wrong way all the time.
Right way is to create Credential object and set Access token using setAccessToken() method.
public static Urlshortener newUrlshortener() {
Credential credential = new Credential();
credential.setAccessToken("{accessToken}");
return new Urlshortener.Builder(new UrlFetchTransport(), new JacksonFactory(), credential)
.build();
}
Upvotes: 1