【发布时间】:2015-11-13 06:42:45
【问题描述】:
我看到其他人遇到过这个问题,但没有一个帖子能够帮助我。我正在尝试将 Volley 用于我的 REST 调用库,当我尝试使用带有 JSON 对象作为参数的 Put 调用时,我得到了error with: org.json.JSONException: End of input at character 0 of。
代码如下:
protected void updateClientDeviceStatus(Activity activity, final int status) {
JSONObject jsonParams = new JSONObject();
try {
jsonParams.put("statusId", String.valueOf(status));
} catch (JSONException e1) {
e1.printStackTrace();
}
Log.i(LOG_TAG, "json: " + jsonParams.toString());
String url = Constants.API_URL + "client/device/" + getDeviceId();
// Request a response from the provided URL.
JsonObjectRequest request = new JsonObjectRequest
(Request.Method.PUT, url, jsonParams, new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
Log.i(LOG_TAG, "updated client status");
Log.i(LOG_TAG, "response: " + response.toString());
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.i(LOG_TAG, "error with: " + error.getMessage());
if (error.networkResponse != null)
Log.i(LOG_TAG, "status code: " + error.networkResponse.statusCode);
}
}) {
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("User-Agent", getUserAgent());
params.put("X-BC-API", getKey());
return params;
}
@Override
public String getBodyContentType() {
return "application/json";
}
};
request.setRetryPolicy(new DefaultRetryPolicy(20000, 3, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
MySingleton.getInstance(activity).addToRequestQueue(request);
}
}
jsonParams 日志显示:
json: {"statusId":"1"}
我还缺少其他设置吗?该请求似乎无法解析 JSON 对象。我什至尝试创建一个 HashMap,然后使用它来创建一个 JSON 对象,但我仍然得到相同的结果。
【问题讨论】:
-
此错误来自您的服务器端。由于来自服务器的响应没有以正确的 json 格式发送。使用 PostMan 或任何其他 API 测试环境确保 api 是否正常工作。
-
尝试使用
Request.Method.POST -
响应为空。如果响应中返回的字符串为空,则调用 JSON 异常。空字符串不能转换为 JSON 对象——它可能为 null,但库决定改为抛出异常。如果您根本没有收到回复,您可以简单地使用 StringRequest。
标签: java android json rest android-volley