Java中的HTTP标头编码/解码 [英] HTTP headers encoding/decoding in Java

查看:253
本文介绍了Java中的HTTP标头编码/解码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

自定义HTTP标头正在传递给Servlet应用程序以进行身份​​验证。标题值必须能够包含重音符号和其他非ASCII字符,因此必须使用特定的编码(理想情况下为UTF-8)。



一块Java代码由开发人员控制认证环境:

 字符串firstName = request.getHeader(my-custom-header ); 
字符串decodedFirstName = new String(firstName.getBytes(),UTF-8);

但是这段代码并不适合我:它预设了头值的编码,在我看来,有一种正确的方式来指定一个标题值的编码(我相信从MIME)。



这是我的问题:什么是正确的方式tm)处理需要支持UTF-8编码的自定义标题值:


  • 在线上(标题的外观如何从解码的角度来看(如何使用Java Servlet API对它进行解码),并且我们可以假设request.getHeader()已经正确地解码了)
  • >


这是一个与环境无关的代码示例,以便在您无法更改服务时将标头作为UTF-8处理:

 字符串valueAsISO = request.getHeader(my-custom-header); 
String valueAsUTF8 = new String(firstName.getBytes(ISO8859-1),UTF-8);


解决方案

同样:RFC 2047在实践中未实现。 HTTP / 1.1的下一个版本将删除任何提及的内容。

所以,如果你需要传输非ASCII字符,最安全的方法是编码它们转换为ASCII序列,例如Atom发布协议中的Slug头文件。


A custom HTTP header is being passed to a Servlet application for authentication purposes. The header value must be able to contain accents and other non-ASCII characters, so must be in a certain encoding (ideally UTF-8).

I am provided with this piece of Java code by the developers who control the authentication environment:

String firstName = request.getHeader("my-custom-header"); 
String decodedFirstName = new String(firstName.getBytes(),"UTF-8");

But this code doesn't look right to me: it presupposes the encoding of the header value, when it seemed to me that there was a proper way of specifying an encoding for header values (from MIME I believe).

Here is my question: what is the right way (tm) of dealing with custom header values that need to support a UTF-8 encoding:

  • on the wire (how the header looks like over the wire)
  • from the decoding point of view (how to decode it using the Java Servlet API, and can we assume that request.getHeader() already properly does the decoding)

Here is an environment independent code sample to treat headers as UTF-8 in case you can't change your service:

String valueAsISO = request.getHeader("my-custom-header"); 
String valueAsUTF8 = new String(firstName.getBytes("ISO8859-1"),"UTF-8");

解决方案

Again: RFC 2047 is not implemented in practice. The next revision of HTTP/1.1 is going to remove any mention of it.

So, if you need to transport non-ASCII characters, the safest way is to encode them into a sequence of ASCII, such as the "Slug" header in the Atom Publishing Protocol.

这篇关于Java中的HTTP标头编码/解码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆