我正在创建一个Android应用程序,它从google电子表格中读取数据,并从用户输入中获取新值,以更新/创建同一电子表格中的一行或更多行。
实际上,在同一个应用程序中,我可以使用GET方法成功地访问电子表格中的数据,接收一个JSON对象并使用以下代码获取所需的数据:
String requestUrl = https://sheets.googleapis.com/v4/spreadsheets/{spreadsheetId}/values/A1:F200?key={myAPIkey}
URL url = createUrl(requestUrl);
HttpsURLConnection urlConnection = (HttpsURLConnection) url.openConnection();
try { urlConnection.setReadTimeout(10000);
urlConnection.setConnectTimeout(15000);
urlConnection.setRequestMethod("GET");
urlConnection.connect(); } finally {
urlConnection.disconnect();
}
但是,当我尝试使用"POST“方法将用户数据写入相同的电子表格时,我得到了错误401,我使用以下代码进行连接:
String requestUrl = https://sheets.googleapis.com/v4/spreadsheets/{spreadsheetId}/values/A5:F5:append?valueInputOption=USER_ENTERED&key={myAPIkey}
URL url = createUrl(requestUrl);
HttpsURLConnection urlConnection = (HttpsURLConnection) url.openConnection();
try {
urlConnection.setDoOutput(true);
urlConnection.setRequestMethod("POST");
urlConnection.setChunkedStreamingMode(0);
OutputStream outputStream = new BufferedOutputStream(urlConnection.getOutputStream());
OutputStreamWriter out = new OutputStreamWriter(urlConnection.getOutputStream());
out.write(object);
out.flush();
out.close();
} finally {
urlConnection.disconnect();
}
您能告诉我为什么会出现401错误吗?如何将数据添加到google电子表格?
我已经将我的电子表格隐私设置为public &任何人都可以使用link进行编辑,但我得到了相同的错误。
发布于 2017-02-24 03:32:50
我认为问题在于您没有通过任何身份验证。401是“未经授权”的响应。如果电子表格是公共的,则可以在没有授权的情况下减少读取,但从API写入需要授权,即使电子表格是公共的。
您应该考虑使用Sheets API client libraries,它为您简化了工作并使身份验证变得更容易。
https://stackoverflow.com/questions/42423264
复制相似问题