简体   繁体   中英

Sending access token back to google api (401 error) using HttpUrlConnection

I wanted to access Google Analytics Management API to create views and had tested getting an access token by OAuth Playground using the scope as analytics.edit. The token was tested valid. However, i keep getting a 401 error on running my code

My code is as below, the language coded is in java

//where urlStr is https://www.googleapis.com/analytics/v3/management/accounts/accountId/webproperties/webPropertyId/profiles with relevant account id, web propertyId and inclusive of request body

String authEncoded = Base64.encodeBytes(accessToken.getBytes());

HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setDoOutput(true);
connection.setRequestProperty("Authorization", "Basic " + authEncoded);
OutputStream output = connection.getOutputStream();


output.write(query.getBytes("UTF-8"));


InputStream response = connection.getInputStream();

Above codes are surrounded in try catch of IOException. However, the response from input stream always give me an error

"java.io.IOException: Server returned HTTP response code: 401 for URL:"

Is there anything i miss out on or is there any other way to set the access token to be send to the google api?

Using oauth.io / android , you can directly build your request with the infos it provide:

data.http(urlStr, new OAuthRequest() {
    private URL url;
    private HttpURLConnection con;

    @Override
    public void onSetURL(String _url) {
        try {
            url = new URL(_url);
            con = (HttpURLConnection) url.openConnection();
        } catch (Exception e) { e.printStackTrace(); }
    }

    @Override
    public void onSetHeader(String header, String value) {
        con.addRequestProperty(header, value);
    }

    @Override
    public void onReady() {
        InputStream response = con.getInputStream();
        // ...
    }
});

Here is a full example: https://github.com/oauth-io/oauth-android/blob/master/example/MainActivity.java

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