OAuth2 + Webmasters Google API: download latest links for SEO, Unauthorized error 401

243 views Asked by At

INTRO

In order to automate some reports I registered a project on Google Developer Console, enabled Webmaster Tools API, Site Verification API.

(For scopes:

 String [] SCOPESArray= {"https://www.googleapis.com/auth/webmasters", 
                      "https://sites.google.com/feeds/"};

)

Then I've built service account credential in my Java application:

 GoogleCredential credential = new  GoogleCredential.Builder().setTransport(httpTransport)
                    .setJsonFactory(jsonFactory)
                    .setServiceAccountId(SERVICE_ACCOUNT_EMAIL)
                    .setServiceAccountScopes(SCOPES)
                    .setServiceAccountPrivateKeyFromP12File(p12)
                    .build();

and service:

    Webmasters service = new Webmasters.Builder(httpTransport, jsonFactory, credential).setApplicationName("APP NAME").build();

Then I've successfully got all sites that are verified:

 Webmasters.Sites.List request = service.sites().list();
   SitesListResponse siteList = request.execute();
   for (WmxSite currentSite : siteList.getSiteEntry()) {
    System.out.println(currentSite+": "+ currentSite.getPermissionLevel());
    }

Output:

{"permissionLevel":"siteFullUser","siteUrl":"http://www.mysite1.com/"}: siteFullUser
{"permissionLevel":"siteOwner","siteUrl":"http://www.mysite2.net/"}: siteOwner

THE PROBLEM:

How to download latest links *.csv file from page Search Traffic\Links to my site? (Page https://www.google.com/webmasters/tools/external-links-domain?hl=en&siteUrl=http://www.mysite2.net/ contains link to this file).

My idea was to use request as first step:

String access_token = credential.getAccessToken();
HttpRequestFactory requestFactory = service.getRequestFactory(); 
GenericUrl url = new GenericUrl("https://www.google.com/webmasters/tools/external-links-domain?hl=en&siteUrl=http://www.mysite2.net/?access_token="+access_token);
HttpRequest httpRequest = requestFactory.buildGetRequest(url);
HttpResponse response = httpRequest.execute();

But I get an error:

HTTP/1.1 401 Unauthorized
Alternate-protocol: 443:quic,p=1
Content-length: 147
X-xss-protection: 1; mode=block
X-content-type-options: nosniff
Transfer-encoding: chunked
Expires: Sat, 13 Jun 2015 17:00:20 GMT
Server: GSE
-content-encoding: gzip
Cache-control: private, max-age=0
Date: Sat, 13 Jun 2015 17:00:20 GMT
X-frame-options: SAMEORIGIN
Content-type: text/html; charset=UTF-8
Www-authenticate: Bearer realm="https://www.google.com/accounts/"

Note: Previous combination OAuth + Webmaster (V2) worked fine for me: the response to analogous request contained link to desired *.csv file

0

There are 0 answers