简体   繁体   中英

How to authorize URL shorten request using Google URL Shortener API for Java

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();

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();

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM