【问题标题】:Encoding problems with @RequestHeader@RequestHeader 的编码问题
【发布时间】:2019-02-22 02:38:04
【问题描述】:

我正在尝试获取包含土耳其字符的标题值,例如“ı,ğ,ü,ş,ö,ç”。我尝试将 ISO-8859-1 编码支持添加到 Spring Boot 配置中,但未能成功。这是application.properties文件内容

spring.http.encoding.charset=ISO-8859-1
spring.http.encoding.enabled=true
spring.http.encoding.force=true
spring.http.encoding.force-request=true
spring.http.encoding.force-response=true

这是一个示例 post 映射,它以 name 参数作为请求标头。

import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class SampleController {

    @PostMapping(value = "/api/hello", consumes = "application/json", produces = "application/json")
    public ResponseEntity<String> samplePost(@RequestHeader("name") String name)  {
        System.out.println("name : " + name);
        return ResponseEntity.ok("Hello " + name);
    }
}

您可以在下面找到示例 curl 和 System.out.println 结果

卷曲:

curl -X POST   http://127.0.0.1:8080/api/hello   -H 'Accept: application/json'   -H 'Content-Type: application/json; charset=UTF-8'   -H 'name: ığüşöç'

输出:

name : ıÄüÅöç

有什么想法吗?

【问题讨论】:

    标签: spring spring-boot encoding


    【解决方案1】:

    你应该在 http-headers 中使用 url-encoding:

    $ curl -X POST   http://127.0.0.1:8080/api/hello   -H 'Accept: application/json'   -H 'Content-Type: application/json; charset=UTF-8'   -H 'name: %C4%B1%C4%9F%C3%BC%C5%9F%C3%B6%C3%A7'
    
    package pro.kretov.spring.boot;
    
    import org.springframework.http.ResponseEntity;
    import org.springframework.web.bind.annotation.PostMapping;
    import org.springframework.web.bind.annotation.RequestHeader;
    import org.springframework.web.bind.annotation.RestController;
    
    import java.io.UnsupportedEncodingException;
    import java.net.URLDecoder;
    
    @RestController
    public class SampleController {
    
        @PostMapping(value = "/api/hello", consumes = "application/json", produces = "application/json")
        public ResponseEntity<String> samplePost(@RequestHeader("name") String name) throws UnsupportedEncodingException {
    
            System.out.println("name : " + URLDecoder.decode(name, "UTF-8"));
            return ResponseEntity.ok("Hello " + URLDecoder.decode(name, "UTF-8"));
        }
    }
    

    回复:

    Hello ığüşöç
    

    application.properties 为空。

    【讨论】:

    • 您好 Wexx,感谢您的回复,但 System.out.println 的结果仍然相同。我也使用“ISO-8859-1”字符集,但结果没有改变。
    猜你喜欢
    • 2011-04-13
    • 2017-11-10
    • 1970-01-01
    • 2023-04-04
    • 2017-03-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多