【问题标题】:How to authorize URL shorten request using Google URL Shortener API for Java如何使用适用于 Java 的 Google URL Shortener API 授权 URL 缩短请求
【发布时间】:2013-05-05 19:31:48
【问题描述】:

我正在开发需要发送授权缩短 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();

【问题讨论】:

    标签: java google-api-java-client google-url-shortener


    【解决方案1】:

    我一直在做错事。

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-03-01
      • 1970-01-01
      • 1970-01-01
      • 2017-02-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多