Preventing Tomcat from appending charset to binary content types

六眼飞鱼酱① 提交于 2020-01-05 07:36:10

问题


We have a Restlet based service that returns the following response:

HTTP/1.1 200 OK
Server: Apache-Coyote/1.1, Restlet-Framework/2.0.7
X-Powered-By: Servlet 2.4; JBoss-4.2.3.GA (build: SVNTag=JBoss_4_2_3_GA date=200807181417)/JBossWeb-2.0
Content-Disposition: inline; filename=Time_for_a_breather.pdf
Date: Fri, 13 May 2011 23:41:24 GMT
Accept-Ranges: bytes
Content-Type: application/pdf;charset=UTF-8
Content-Length: 218495

but unfortunately within some browsers (Chrome in particular) we are having problems viewing the pdf.

From experimenation and research it appears the problem is related to jBoss/Tomcat appending charset=UTF-8 to the Content Type which causes the browser to sense that its receiving text data not binary data.

Does anybody know of a way from preventing jBoss/Tomcat appending the charset to the content type for binary data?


回答1:


At this stage I have been unable to stop Tomcat from appending charset=UTF-8 to the Content-Type header which is causing Chrome PDFViewer (internal PDF viewer) to fail viewing the PDF document.

While experimenting I have discovered that if I don't return the Content-Length and set Transfer-Encoding=chunked then the PDF is viewable by Chrome's PDFViewer. This is a workaround for the moment but probably a fragile solution.




回答2:


The servletcontainer does that only when you have a

response.setCharacterEncoding("UTF-8");

somewhere in your code. See also the javadoc. Setting the character encoding makes no sense for binary data, so just don't do that on requests for binary data.




回答3:


In my case, it turned out to be Spring's CharacterEncodingFilter. If you set forceEncoding to true, it will add the character encoding to the content type, even if it makes no sense as for binary data.

In order to fix it, set the forceEncoding to false or leave it in the default setting. And verify the effect it has, e.g. on JSON responses.



来源:https://stackoverflow.com/questions/5998875/preventing-tomcat-from-appending-charset-to-binary-content-types

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!