我想访问 Google Analytics Management API 以创建 View ,并测试了通过 OAuth Playground 使用 analytics.edit 范围获取访问 token 。 token 经测试有效。但是,我在运行代码时不断收到 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:服务器为 URL 返回 HTTP 响应代码:401:”
有没有我遗漏的东西,或者有没有其他方法可以设置要发送到 google api 的访问 token ?
最佳答案
使用 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
关于java - 使用 HttpUrlConnection 将访问 token 发送回 google api(401 错误),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21213864/