我想访问Google Analytics Management API以创建视图,并已使用范围analytics.edit测试了OAuth Playground获取访问令牌的情况。令牌测试有效。但是,我在运行代码时遇到401错误
我的代码如下,编码的语言是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();
以上代码包含在IOException的try catch中。但是,输入流的响应总是给我一个错误
“java.io.IOException:服务器返回HTTP响应代码:401为URL:”
我有什么遗漏或有没有其他方法来设置访问令牌发送到谷歌API?
答案 0 :(得分:1)
使用oauth.io / android,您可以使用它提供的信息直接构建您的请求:
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();
// ...
}
});
以下是一个完整的示例:https://github.com/oauth-io/oauth-android/blob/master/example/MainActivity.java