spring - @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 : ıÄüÅöç
任何想法?
解决方案
您应该在 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 为空。
推荐阅读
- python - 我使用 Kivy UrlReguest 下载并显示 Json 文件,但在 android 上没有任何效果,为什么?
- c# - 检测 C# 表单外的鼠标点击
- node.js - 如何在 NestJS 和 Jest 中测试 .map() 函数
- python - 在python中将大文件(500MB +)编码为base64
- tensorflow - 使用我的自定义损失函数时出现此错误:“张量”对象没有属性“_numpy”
- sql - Laravel Query Builder 加入别名
- tmap - tmap_save 中的错误:找不到对象“tm”
- plot - Seaborn 固定线图高度
- python - tflite 对象检测中的 Raspberry Pi GPIO 引脚问题
- extjs - 安装 ExtJs 7 GPL 版本时的试用水印