响应中的内容类型标头由charset = ISO-8859-1附加

时间:2019-07-19 06:37:49

标签: web-services character-encoding content-type

我有一个生成 MediaType.APPLICATION_XML_VALUE

的Web服务

在其余客户端中,我看到内容类型标头为 application / xml; charset = ISO-8859-1

呼叫者已将Accept标头设置为 application / xml

不确定是什么在标题中添加了charset = ISO-8859-1。

要从内容类型标题中删除字符集,

  • 尝试提及 application / xml 而不是 MediaType.APPLICATION_XML_VALUE
  • 尝试添加弹簧过滤器 CharacterEncodingFilter
  • 试图在application.properties文件中添加 spring.http.encoding.force = false

以上所有内容均无影响。

来电者


    curl -v -X POST \
      https://<URL> \
      -H 'Content-Type: application/x-www-form-urlencoded' \
      -H 'accept: application/xml' 

Java资源


    @RequestMapping(value = "<URL>",
                    method = RequestMethod.POST, consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE,
                    produces = MediaType.APPLICATION_XML_VALUE)
    @ResponseBody
    public String processRequest(HttpServletRequest request) {
        try {
            Object response = service(request);
            if (response != null) {
                return response.toString();
            }
        } catch (Exception e) {
            logger.error(e);
        }
        return createErrorResponse(ERR_CODE).toString();
    }

// response header
200 OK
Time:1247 ms
Size:1.62 KB
Save
Download
Date →Wed, 17 Jul 2019 07:30:28 GMT
Server →Apache
Strict-Transport-Security →max-age=31536000; includeSubDomains
Content-Type →application/xml;charset=ISO-8859-1
Content-Length →1374
Via →1.1 <URL>
Keep-Alive →timeout=5, max=10000
Connection →Keep-Alive

这很好。开始看到以下行为,升级以下库之后


    jackson 2.6.0 to 2.6.3
    httpclient 4.5 to 4.5.3
    httpcomponents 4.4.1 to 4.4.6
    springframework 4.2.9 to 4.3.17

需要知道一种方法,该方法如何从标头中省略字符集,以及首先添加它的原因。

1 个答案:

答案 0 :(得分:0)

找到了问题。

@ResponseBody注释将字符串输出转换为HTTP支持的格式。

在内部,如果未指定,它将charset=ISO-8859-1附加到内容类型标题中。

由于我要删除此内容,因此更改后的方法从String返回到ResponseEntity<String> ResponseEntity将负责将输出转换为HTTP支持的格式,而不是注释。因此,现在可以使用代码控制转换为HTTP,而不是让spring做。在这里,我们可以显式设置所需的标题。

新代码如下:

@RequestMapping(value = "<URL>",method = RequestMethod.POST, consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE,produces = MediaType.APPLICATION_XML_VALUE)
public ResponseEntity<String> processRequest(HttpServletRequest request) {
    try {
        Object response = service(request);
        if (response != null) {
            prepareResponseEntity(response.toString());
        }
    } catch (Exception e) {
        logger.error(e);
    }
    return prepareResponseEntity(createErrorResponse(ERR_CODE).toString());
}

private static ResponseEntity<String> prepareResponseEntity (String responseBody){
    HttpHeaders responseHeaders = new HttpHeaders();
    responseHeaders.add(HeartBeatServerConstants.HEADER_CONTENT_TYPE,MediaType.APPLICATION_XML_VALUE);
    return new ResponseEntity<String>(responseBody,responseHeaders,HttpStatus.OK);  
}

更新:spring-web的AbstractHttpMessageConverter在spring 4.2.9和4.3.17之间进行了更改,以添加不存在的字符集。Spring Doc

相关问题