[英]Retrofit2 204 No Content has content exception
我从服务器空的json(“ {}”)获取,其删除响应为代码204。
在okhttp3.internal.http.HttpEngine
类中,抛出了这个令人讨厌的东西:
if ((code == 204 || code == 205) && response.body().contentLength() > 0) {
throw new ProtocolException(
"HTTP " + code + " had non-zero Content-Length: " + response.body().contentLength());
}
如果尝试在标头中返回内容(服务器端)无内容的内容,则Content-Length仍大于0;
任何非服务器端的想法如何解决此问题?
您可以将ProtocolException
捕获在拦截器中,并返回占位符204 Response
。 使用此方法的警告-1)您可能最终会陷入其他协议错误(重定向太多等)。 如果这是一个问题,则可以将e.getMessage()
与okhttp的异常消息进行比较,如果没有匹配项,则将异常抛出。 2)您仍然无权访问原始响应,因此如果您不走运,则需要检查返回的任何标头。
OkHttpClient.Builder builder = new OkHttpClient.Builder();
builder.addNetworkInterceptor(new Interceptor() {
@Override
public Response intercept(Chain chain) throws IOException {
Response response;
try {
response = chain.proceed(chain.request());
} catch (ProtocolException e) {
response = new Response.Builder()
.request(chain.request())
.code(204)
.protocol(Protocol.HTTP_1_1)
.build();
}
return response;
}
});
如果稍有不同,可以避免这种情况。 代替:
@DELETE("vehicles/{id}/")
Observable<Response<BaseResponse>> deleteVehicle(@Header("Authorization") String token, @Path("id") Long vehicleId);
我用:
@HTTP(method = "DELETE", path = "vehicles/{id}/", hasBody = true)
Observable<Response<BaseResponse>> deleteVehicle(@Header("Authorization") String token, @Path("id") Long vehicleId);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.