Sur*_*wat 6 spring response utf-8 character-encoding resttemplate
我在jetty web服务器(还有tomcat)上运行基于注释的Spring Rest服务。控制器代码是:
\n\n@RequestMapping(method = RequestMethod.POST, value = { "/ssrfeed/exec/",\n "/query/exec" }, consumes = { "application/xml", "text/xml",\n "application/x-www-form-urlencoded" }, produces = {\n "application/xml;charset=UTF-8", "text/xml;charset=UTF-8",\n "application/x-www-form-urlencoded;charset=UTF-8" })\n @ResponseBody\n protected String getXmlFeed(HttpServletRequest request,\n @PathVariable String serviceName, @RequestBody String xmlReq) {\n\n //code....\n return appXMLResponse;\n }\nRun Code Online (Sandbox Code Playgroud)\n\n问题是控制器返回的响应 xml 包含一些字符,例如 \xc3\xa4 \xc3\xb6 \xc3\xbc (Umlaute)。在浏览器上呈现时的响应给出解析错误:
\n\nXML Parsing Error: not well-formed\nLocation: //localhost:8083/MySerice/ssrfeed/exec/\nLine Number 18111, Column 17:\n<FIRST_NAME>Tzee rfista</FIRST_NAME>\n----------------^\nRun Code Online (Sandbox Code Playgroud)\n\n(\xc3\xbc 的位置出现一个小三角形)
\n\nThe expected is : <FIRST_NAME>Tzee\xc3\xbcrfista</FIRST_NAME>\nRun Code Online (Sandbox Code Playgroud)\n\n我已尝试以下解决方案,但问题仍然存在。
\n\n尝试使用过滤器参考technowobble上给出的解决方案
将字符集传递给 StringHttpMessageConverter 属性
\n\n<bean id="restTemplate" class="org.springframework.web.client.RestTemplate">\n <property name="messageConverters">\n <list>\n <bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">\n <property name="supportedMediaTypes" value="application/json" />\n </bean>\n <bean class="org.springframework.http.converter.StringHttpMessageConverter">\n <property name="supportedMediaTypes" value="text/xml;charset=UTF-8" />\n </bean>\n </list>\n </property>\n</bean>\nRun Code Online (Sandbox Code Playgroud)\n\nSetCharacterEncodingFilter在 tomcat -web.xml 中启用
将代码更改为 returnResponseEntity而不是String并删除@ResponseBody。
protected ResponseEntity<String> getXmlFeed(HttpServletRequest\nrequest, @PathVariable String serviceName, @RequestBody String xmlReq) { \n//line of code\n HttpHeaders responseHeaders = new HttpHeaders();\n responseHeaders.add("Content-Type", "application/xml; charset=utf-8");\n return new ResponseEntity<String>(appXMLResponse, responseHeaders, HttpStatus.CREATED);\n\n}\nRun Code Online (Sandbox Code Playgroud)第四个解决方案有效,但这是现有代码,我无法更改方法签名,因为它可能会影响该服务的现有客户端。有什么想法/指针来解决这个问题吗?
\n小智 0
在您的调度程序 servlet 上下文 xml 中,您必须添加一个属性。例如
<bean class = "org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<property name="messageConverters">
<array>
<bean class = "org.springframework.http.converter.StringHttpMessageConverter">
<property name="supportedMediaTypes" value = "text/plain;charset=UTF-8" />
</bean>
</array>
</property>
</bean>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
18681 次 |
| 最近记录: |