Reputation: 4020
I've build a custom Spring Web MessageConverter and overridden the writeInternal method.
Should i call flush on the getBody() OutputStream? Should i close the getBody() OutputStream?
there's seems to be quite the mismatch between the different converters.
I was thinking no to both since spring wants to flush the output stream see https://github.com/spring-projects/spring-framework/blob/56db1af11dbe51c88c753421e022bc5389361c04/spring-web/src/main/java/org/springframework/http/converter/AbstractGenericHttpMessageConverter.java#L101
but then i saw the gson is actually closing the stream? is that just a bug or the desired behaviour? https://github.com/spring-projects/spring-framework/blob/56db1af11dbe51c88c753421e022bc5389361c04/spring-web/src/main/java/org/springframework/http/converter/json/GsonHttpMessageConverter.java#L203
and then the StringConverter flushes but doesn't close https://github.com/spring-projects/spring-framework/blob/56db1af11dbe51c88c753421e022bc5389361c04/spring-web/src/main/java/org/springframework/http/converter/StringHttpMessageConverter.java#L107 which calls https://github.com/spring-projects/spring-framework/blob/56db1af11dbe51c88c753421e022bc5389361c04/spring-core/src/main/java/org/springframework/util/StreamUtils.java#L110
so not really seeing a definitive answer in the prior art...
Upvotes: 2
Views: 2368
Reputation: 1067
Never call close() method anywhere.
You should never call close() method as it will immediately disconnect the client socket and their will be no point executing request further on server as the client request is already processed. Also it will trimmed out all the configured post filters and interceptors execution that may results in various error condition.
Why should we not call close method on response stream/writer?
Response stream will be eventually closed by container itself at the end of request processing so you should not worry about calling it manually. Just write your custom converter as you want it to be.
Also you don't need to flush the content as being a buffered output stream, content is automatically being flushed when buffers runs out of the capacity.
Gson converter may have it mistakenly and request will still terminate as soon as json data is written to response stream. As you already know the consequences of using them. If this is really going to create any problem in your case then you can think of MappingJackson2HttpMessageConverter as alternative, it doesn't close the output stream after writing json string into it.
But if you writing a new converter, then it will be a better idea not to close the streams anywhere in the code.
Upvotes: 2