我正在尝试使用POST请求(附加)在Google电子表格中附加值。
使用API密钥(在Google云上生成)基于JsonObjectRequest进行GET请求时,我没有遇到任何错误,并且一切正常。但是,当我尝试使用类似的POST请求(将值插入存储在requestBody中的电子表格中)时,android studio抛出一个错误:
E/Volley: [165] BasicNetwork.performRequest: Unexpected response code 401 for https://sheets.googleapis.com/v4[...rest of my url...]
D/Error.Response: com.android.volley.AuthFailureError
是因为我不正确地编写了请求正文,还是因为我无法验证我的请求?我认为我的身份验证是可以的,因为GET请求没有错误。您能帮我说我的要求出了什么问题吗?
我对android编程和使用REST API还是很陌生,所以也许有些我不了解。我的代码主要基于我在堆栈溢出中发现的内容:
public void getSheetInfo(View view) throws JSONException {
RequestQueue queue = Volley.newRequestQueue(this);
final String url = "https://sheets.googleapis.com/v4/spreadsheets/<HereIsMySpreadsheetID>/values/Sheet1!A1:append?key=<HereIsMyAPIKey>";
JSONObject jsonBody = new JSONObject();
Object a1 = "TEST appended Row 1 Column A";
jsonBody.put("values", a1);
final String requestBody = jsonBody.toString();
StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
new Response.Listener<String>()
{
@Override
public void onResponse(String response) {
Log.d("Response", response.toString());
}
},
new Response.ErrorListener()
{
@Override
public void onErrorResponse(VolleyError error){
Log.d("Error.Response", error.toString());
}
}
) {
@Override
public String getBodyContentType() {
return "application/json; charset=utf-8";
}
@Override
public byte[] getBody() throws AuthFailureError {
try {
return requestBody == null ? null : requestBody.getBytes("utf-8");
} catch (UnsupportedEncodingException uee) {
VolleyLog.wtf("Unsupported Encoding while trying to get the bytes of %s using %s", requestBody, "utf-8");
return null;
}
}
@Override
protected Response<String> parseNetworkResponse(NetworkResponse response) {
String responseString = "";
if (response != null) {
responseString = String.valueOf(response.statusCode);
}
return Response.success(responseString, HttpHeaderParser.parseCacheHeaders(response));
}
};
queue.add(stringRequest);
}