加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

java – 在spring-boot rest和Swagger的头文件中使用utf-8字符

发布时间:2020-12-15 01:47:15 所属栏目:大数据 来源:网络整理
导读:我有一个招摇的春天启动应用程序.当我测试我的休息服务时,标题中没有utf-8字符,一切正常. Swagger生成命令,我可以使用它来测试它: curl -X GET --header 'Accept: application/json' --header 'user: me' --header 'reason: zst' --header 'Authorization:

我有一个招摇的春天启动应用程序.当我测试我的休息服务时,标题中没有utf-8字符,一切正常. Swagger生成命令,我可以使用它来测试它:

curl -X GET --header 'Accept: application/json' --header 'user: me' --header 'reason: zst' --header 'Authorization: Basic dG9tYXM6dG9tYXMxMjM=' 'http://localhost:8080/my-app/uuid/756531B55A3D029A0894D7C9C4ACDF3EC0'

但当我在招摇时使用utf-8字符时,我没有得到任何回应. Swagger正在加载一些东西.当我查看firefox的控制台时,我看到一些get请求:

http://localhost:8080/my-app/webjars/springfox-swagger-ui/images/throbber.gif 

没有回应.

当我尝试编辑上面的curl命令时:

curl -X GET --header 'Accept: application/json' --header 'user: me' --header 'reason: ???' --header 'Authorization: Basic dG9tYXM6dG9tYXMxMjM=' 'http://localhost:8080/my-app/uuid/756531B55A3D029A0894D7C9C4ACDF3EC0'

一切正常,所以我猜我的后端没问题.有什么办法可以解决/调试这个问题吗?

最佳答案
根据RFC 2616 section 4,消息头定义如下:

message-header = field-name ":" [ field-value ]
field-name     = token
field-value    = *( field-content | LWS )
field-content  = 

知道根据section 2

token          = 1*

The TEXT rule is only used for descriptive field contents and values
that are not intended to be interpreted by the message parser. Words
of *TEXT MAY contain characters from character sets other than ISO-8859-1 only when encoded according to the rules of 07002
.

TEXT          = 

换句话说,标头的值只能是ISO-8859-1编码,如果你想编码未包含在这个字符集中的字符,这似乎是这里的情况,你应该根据RFC编码它2047也称为MIME(多用途Internet邮件扩展)第三部分:非ASCII文本的邮件头扩展.

而不是

reason: ???

它应该是

reason: =?utf-8?q?=C5=BE=C5=A1=C5=A5?=

实际上,甚至建议在不使用US-ASCII字符时对值进行编码.

最后要检查的是,如果您的JAX-RS实现支持开箱即用的RFC 2047,如果不是,您将需要手动解码它,例如使用实用程序方法MimeUtility.decodeText(String etext).

这是一个具体的例子:

@GET
public Response showHeader(@HeaderParam("reason") String reason) 
    throws UnsupportedEncodingException {
    // Decode it
    reason = MimeUtility.decodeText(reason);
    // Return the value of the decoded String
    return Response.status(Response.Status.OK)
        .entity(String.format("Value of reason = '%s'",reason))
        .build();
}

使用curl调用此资源方法–header’reason:=?utf-8?q?= C5 = BE = C5 = A1 = C5 = A5?=’按预期给出:

Value of reason = '???'

注意:要从js前端对头的值进行编码,可以使用库q-encoding,这里是live demo.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读