How to put and get UTF-8 string from HTTP header with jersey?

社会主义新天地 提交于 2021-01-27 18:09:43

问题


I have a problem that I was asked to put some of the parameters into HTTP header of the request. The web server (with jersey 1.17) will parse the parameters from the header fields. However, the values of the parameters should be formed by UTF-8. Is it possible to put an UTF-8 string in the HTTP header? If it is possible, how can I simulate it using rest client (such as RESTClient in Firefox plugin)?

I have tried to search for this question by google, and a question (What character encoding should I use for a HTTP header?) seems relative to my question. The response said that HTTP header use MIME encoding only when the character set is not ISO-8859-1. If this is true, how can I parse MIME encoding in jersey to get the correct UTF-8 string from the request header?

Many thanks!


回答1:


Thanks to Eugen, I have found the solution.

Since RFC defines that header can accept MIME encoding, the answer is to put an encoded string on the header field before sending HTTP request through RestClient. For server which receives the request in jersey, get the string from header and decode the string using MIME decoder.

For example:

@GET
@Path("/get")
public Response get (@Context HttpHeaders headers) {
    // Get the value from header, where "header-name" is the key name of the header.
    String value = headers.getRequestHeader("header-name").get(0);
    // Decode the value using MIME decoder.
    try {
        value = javax.mail.internet.MimeUtility.decodeText(value);
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }
    System.out.println("Decoded value from header: " + value);
    return Response.ok().build();
}


来源:https://stackoverflow.com/questions/19245695/how-to-put-and-get-utf-8-string-from-http-header-with-jersey

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!