我正在开发GAE应用程序,它需要发送授权的shorten请求,以便它们显示在用户http://goo.gl仪表板中。我使用Google URL shortener API for Java library (google-api-services-urlshortener-v1-rev12-1.12.0-beta.jar)的方式如下:
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();
}我的请求得到处理,我可以检索短网址,但它不会显示在用户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/"}'我也试过在request中添加授权HttpHeader,但不起作用:
HttpHeaders headers = new HttpHeaders();
headers.put("Authorization", "Bearer {sameAccessToken}");
inserted = shortener.url().insert(toInsert).setRequestHeaders(headers).execute();发布于 2013-05-07 05:55:21
我一直在用错误的方式去做。
正确的方法是创建Credential对象并使用setAccessToken()方法设置访问令牌。
public static Urlshortener newUrlshortener() {
Credential credential = new Credential();
credential.setAccessToken("{accessToken}");
return new Urlshortener.Builder(new UrlFetchTransport(), new JacksonFactory(), credential)
.build();
}https://stackoverflow.com/questions/16388309
复制相似问题