retrofit: HTTP 204/205 bypass converter and unconditionally send null to adapter
I stumbled upon this: https://github.com/square/retrofit/issues/1554 and added a converter because I wanted to handle the empty response body and not pass it as null to Observable. That thread is talking about code 200 and empty body though.
Then I found out that in the current Retrofit version no converter is called at all for 204 and 205:
if (code == 204 || code == 205) {
rawBody.close();
return Response.success(null, rawResponse);
}
This forces me to use Single<Response<SomeModel>>
instead of Single<SomeModel>
I was hoping to use…
I understand that 204 stands for no content, so it’s only logical to pass the response as null. But for my specific case, I would prefer to handle 204 in onError
, so I hoped to handle the empty body in the converter and just throw a custom error there instead.
Is there any chance that approach will be changed? I am relatively new to Retrofit but I am used to Alamofire on iOS and there it’s possible to specify during configuration what is treated as a successful response code:
.validate(statusCode: 200)
So every code that is not on that list would be handled as an error.
About this issue
- Original URL
- State: open
- Created 6 years ago
- Reactions: 9
- Comments: 16 (7 by maintainers)
Inspired from the snippet just above, I made a version that doesn’t fail when the server responds with a content length of zero, and is lenient if there’s actually some content:
A quick workaround for those who want to start using the 2.6.0, add the below as your first interceptor in OkHttp client. After that, you would be able to call services which returns 204 / 205 as such:
Regards
I’ve solved the issue by (in Interceptor):
return if (response.code == 204 || response.code == 205) { response.newBuilder() .code(200) .body("{}".toResponseBody()) .build() } else { response }
Yes. Retrofit depend on OkHttp 3.14 and the latest binary compatible release is 4.9.
You should still propagate headers
Also inspired from the snippets above, here is my version:
If you need to error the request out, you can detect 204 in OkHttp Interceptor and throw a error, sorry I misinterpret the issue, I though you wanted to handle 204 as 200.