如何授权URL缩短请求使用谷歌URL缩短API的Java



我正在开发GAE应用程序,该应用程序需要发送授权的缩短URL请求,以便它们显示在用户http://goo.gl仪表板中。我使用Google URL缩短API的Java库(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();
  }

我的请求得到处理,我可以检索短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/"}'

我也试过添加授权HttpHeader请求,但它没有工作:

HttpHeaders headers = new HttpHeaders();
        headers.put("Authorization", "Bearer {sameAccessToken}");
        inserted = shortener.url().insert(toInsert).setRequestHeaders(headers).execute();

我一直在用错误的方式做事。

正确的方法是创建凭据对象并使用setAccessToken()方法设置访问令牌

public static Urlshortener newUrlshortener() {
    Credential credential = new Credential();
    credential.setAccessToken("{accessToken}");
    return new Urlshortener.Builder(new UrlFetchTransport(), new JacksonFactory(), credential)
    .build();
}

最新更新