首页 > 解决方案 > @RequestHeader 的编码问题

问题描述

我正在尝试获取包含土耳其字符的标题值,例如“ı,ğ,ü,ş,ö,ç”。我尝试将 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

这是一个将名称参数作为请求标头的示例发布映射。

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 : ıÄüÅöç

任何想法?

标签: springspring-bootencoding

解决方案


您应该在 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 为空。


推荐阅读