承認された短縮 URL 要求を送信する必要がある GAE アプリケーションを開発しているため、ユーザーのhttp://goo.glダッシュボードに表示されます。次の方法で、Java ライブラリ (google-api-services-urlshortener-v1-rev12-1.12.0-beta.jar) 用の Google URL 短縮 API を使用しています。
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();
}
リクエストが処理され、短い URL を取得できますが、ユーザーのhttp://goo.leダッシュボードに表示されません。
curl を使用して実行できますが、正常に動作します。リクエストはユーザー ダッシュボードに表示されます。
curl https://www.googleapis.com/urlshortener/v1/url -H 'Content-Type: application/json' -H 'Authorization: Bearer {sameAccessToken}' -d '{"longUrl": "http://www.google.com/"}'
Authorization HttpHeader をリクエストに追加しようとしましたが、うまくいきませんでした:
HttpHeaders headers = new HttpHeaders();
headers.put("Authorization", "Bearer {sameAccessToken}");
inserted = shortener.url().insert(toInsert).setRequestHeaders(headers).execute();