@RequestHeader

时间:2019-02-21 17:42:39

标签: spring spring-boot encoding

我正在尝试获取包含土耳其字符(例如“ı,ğ,ü,ş,ö,ç”)的标头值。我尝试在弹簧启动配置中添加ISO-8859-1编码支持,但未能成功。这是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

这是一个将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 : ıÄüÅöç

有什么主意吗?

1 个答案:

答案 0 :(得分:1)

您应该在http-header中使用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为空。