Volley JSONException:输入结束于字符 0

Volley JSONException: End of input at character 0 of

我看到其他人遇到过这个问题,但是 none 的帖子能够帮助我。我正在尝试将 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 对象,但我仍然得到相同的结果。

我也遇到过这个问题

这不一定是因为您的服务器端出现问题 - 它只是意味着 JsonObjectRequest 的响应为空。

很可能服务器应该向您发送内容,而其响应为空的事实是一个错误。但是,如果这是服务器的行为方式,那么要解决此问题,您将需要更改 JsonObjectRequest 解析其响应的方式,这意味着创建 JsonObjectRequest 的子类并覆盖 parseNetworkResponse到下面的例子。

    @Override
    protected Response<JSONObject> parseNetworkResponse(NetworkResponse response) {
        try {
            String jsonString = new String(response.data,
                    HttpHeaderParser.parseCharset(response.headers, PROTOCOL_CHARSET));

            JSONObject result = null;

            if (jsonString != null && jsonString.length() > 0)
                 result = new JSONObject(jsonString);

            return Response.success(result,
                    HttpHeaderParser.parseCacheHeaders(response));
        } catch (UnsupportedEncodingException e) {
            return Response.error(new ParseError(e));
        } catch (JSONException je) {
            return Response.error(new ParseError(je));
        }
    } 

请记住,通过此修复,如果服务器响应为空,请求回调将 return 空引用代替 JSONObject

可能没有意义,但除了添加 content-type header

对我没有其他作用
mHeaders.put("Content-Type", "application/json");

就我而言,这只是我发送的请求 (POST) 不正确。我交叉检查了我的字段并注意到存在不匹配,这是服务器期望得到的错误->输入结束字符 0 of...

我遇到了同样的问题,我通过创建一个可以捕获 null 或空响应的自定义 JsonObjectRequest 来修复它:

public class CustomJsonObjectRequest extends JsonObjectRequest {

public CustomJsonObjectRequest(int method, String url, JSONObject jsonRequest, Response.Listener<JSONObject> listener, Response.ErrorListener errorListener) {
    super(method, url, jsonRequest, listener, errorListener);
}

public CustomJsonObjectRequest(String url, JSONObject jsonRequest, Response.Listener<JSONObject> listener, Response.ErrorListener errorListener) {
    super(url, jsonRequest, listener, errorListener);
}

@Override
protected Response<JSONObject> parseNetworkResponse(NetworkResponse response) {
    try {
        String jsonString = new String(response.data,
                HttpHeaderParser.parseCharset(response.headers));

        JSONObject result = null;

        if (jsonString != null && jsonString.length() > 0)
            result = new JSONObject(jsonString);

        return Response.success(result,
                HttpHeaderParser.parseCacheHeaders(response));
    } catch (UnsupportedEncodingException e) {
        return Response.error(new ParseError(e));
    } catch (JSONException je) {
        return Response.error(new ParseError(je));
    }
}

那就把默认的 JsonObjectRequest 换成这个吧!

您需要检查服务器响应是否不为空。也许它可能是一个 emtply String "".

        if (response.success()) {
            if (response.getData() == null) {
                return null;
            } else if (response.getData().length() <= 0){
                return null;
            }

           // Do Processing
            try {

我遇到了同样的问题,只是发生了一个小愚蠢的错误。

而不是

val jsonObject = JSONObject(response.body()?.string())

应该是

val jsonObject = JSONObject(response.body()!!.string())