Android Volley库没有使用204和空身反应

Ank*_*r22 5 android android-volley http-status-code-204

我正在使用最新的Volley库,当我的api返回204而没有响应的身体时,我遇到了问题.似乎BasicNetwork.java中的以下代码未按预期工作:

// Some responses such as 204s do not have content.  We must check.
if (httpResponse.getEntity() != null) {
    responseContents = entityToBytes(httpResponse.getEntity());
} else {
    // Add 0 byte response as a way of honestly representing a
    // no-content request.
    responseContents = new byte[0];
}
Run Code Online (Sandbox Code Playgroud)

getEntity的结果对我来说永远不会为null,但它是空的.我已经确保我的API没有通过检查卷发和邮递员返回任何内容(只是为了更加确定我不会发疯).还有其他人有这样的问题吗?

现在我刚刚改变了,如果:

if (statusCode != HttpStatus.SC_NO_CONTENT && httpResponse.getEntity() != null)
Run Code Online (Sandbox Code Playgroud)

我知道这不是解决根本原因,但我想确保在深入研究这个问题之前我没有遗漏任何明显的东西.

谢谢!

编辑:对不起,我忘了提到实际问题是在方法entityToBytes中发生超时异常,这很奇怪,因为没有要检索的主体.

此外,我没有使用实际功能齐全的webservice API,因为它尚不可用.相反,我正在连接到养蜂场上的模拟网络服务,但我不知道养蜂场是如何成为问题的.

Cha*_*esA 7

这不仅仅是对您的解决方案的详细阐述!首先,我使用来自我的API的204个回复,并且遇到了完全相同的问题.我使用BasicNetwork.java中的代码来解决它 - 线if (statusCode != HttpStatus.SC_NO_CONTENT && httpResponse.getEntity() != null)

我还发现,如果我使用标准JsonObjectRequest请求,那么Response.ErrorListener将触发因为正文为空.

我创建了一个new JsonObjectRequestWithNull,它在null或空体的情况下提供成功响应.码:

public class JsonObjectRequestWithNull extends JsonRequest<JSONObject> {

public JsonObjectRequestWithNull(int method, String url, JSONObject jsonRequest,
                         Response.Listener<JSONObject> listener, Response.ErrorListener errorListener) {
    super(method, url, (jsonRequest == null) ? null : jsonRequest.toString(), listener,
            errorListener);
}

public JsonObjectRequestWithNull(String url, JSONObject jsonRequest, Response.Listener<JSONObject> listener,
                         Response.ErrorListener errorListener) {
    this(jsonRequest == null ? Request.Method.GET : Request.Method.POST, url, jsonRequest,
            listener, errorListener);
}

@Override
protected Response<JSONObject> parseNetworkResponse(NetworkResponse response) {
    try {
        String jsonString = new String(response.data,
                HttpHeaderParser.parseCharset(response.headers, PROTOCOL_CHARSET));
        //Allow null
        if (jsonString == null || jsonString.length() == 0) {
            return Response.success(null, HttpHeaderParser.parseCacheHeaders(response));
        }
        return Response.success(new JSONObject(jsonString),
                HttpHeaderParser.parseCacheHeaders(response));
    } catch (UnsupportedEncodingException e) {
        return Response.error(new ParseError(e));
    } catch (JSONException je) {
        return Response.error(new ParseError(je));
    }
}
Run Code Online (Sandbox Code Playgroud)

}

相关的一点是:

        //Allow null
        if (jsonString == null || jsonString.length() == 0) {
            return Response.success(null, HttpHeaderParser.parseCacheHeaders(response));
        }
Run Code Online (Sandbox Code Playgroud)

希望对某人有帮助.