Retrofit2 doesn’t handle empty content responses

Ken Yee
1 min readApr 20, 2017

This is another Retrofit2 change that isn’t apparent until you hit it. If your backend returns 200 with a blank response body instead of “{ }” as it should when you’re using a REST API, Retrofit1 returned a null for the response instead of throwing an invalid JSON error that Retrofit2’s converters do now.

The workaround is to add a null delegating converter in front of the JSON converter for Retrofit2.

class NullOnEmptyConverterFactory implements Converter.Factory {
@Override public Converter<ResponseBody, ?> responseBody(Type type, Annotation[] annotations, Retrofit retrofit) {
final Converter<ResponseBody, ?> delegate = retrofit.nextResponseBodyConverter(this, type, annotations);
return new Converter<>() {
@Override public void convert(ResponseBody body) {
if (body.contentLength() == 0) return null;
return delegate.convert(body);
}
};
}
}
Then to add it:
Retrofit retrofit = new Retrofit.Builder()
.endpoint(..)
.addConverterFactory(new NullOnEmptyConverterFactory())
.addConverterFactory(GsonConverterFactory.create())
.build();

Ref: https://github.com/square/retrofit/issues/1554

--

--

Ken Yee

Mobile (Native Android), Backend (Spring Boot, Quarkus), Devops (Jenkins, Docker, K8s) software engineer. Currently Kotlin All The Things!