user3205607
user3205607

Reputation: 41

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?

Upvotes: 2

Views: 1100

Answers (1)

bumpmann
bumpmann

Reputation: 685

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

Upvotes: 1

Related Questions