简体   繁体   English

如何在Apache HTTP Components中设置编码?

[英]How to set encoding in Apache HTTP Components?

How do I set the character encoding in Apache HTTP Components? 如何在Apache HTTP组件中设置字符编码?

I do something like this: 我做这样的事情:

    Form form = Form.form();
    form = form.add("somekey", "somevalue");
    Request request = Request.Post("http://somehost/some-form")
                             .request.bodyForm(form.build());

"somekey" and "somevalue" are unicode strings because all java string are unicode. “somekey”和“somevalue”是unicode字符串,因为所有java字符串都是unicode。 http components converts them to latin-1 when I tested. 我测试时,http组件将它们转换为latin-1。 I want it to convert to something else (eg, utf-8). 我希望它转换为其他东西(例如,utf-8)。

Going by what you've shown in your example, you seem to be using the fluent API. 按照您在示例中显示的内容,您似乎正在使用流畅的API。

Looking into the javadocs there is a version of request.bodyForm() that accepts a charset: 查看javadocs有一个版本的request.bodyForm()接受一个字符集:

    import org.apache.http.Consts;
    ...
    request = request.bodyForm(form.build(), Consts.UTF_8);

According to the source , the charset defaults to Consts.ISO_8859_1 (aka Latin-1). 根据消息来源 ,charset默认为Consts.ISO_8859_1 (又名Latin-1)。

Alternatives 备择方案

  1. If that doesn't work, consider: 如果这不起作用,请考虑:

     import org.apache.http.Consts; ... request.elementCharset(Consts.UTF_8); 
  2. As a last resort, it should be possible to set the content charset. 作为最后的手段,应该可以设置内容字符集。 Looking at the source for elementCharset() , you could try the following: 查看elementCharset()源代码 ,您可以尝试以下方法:

     import org.apache.http.Consts; import org.apache.http.params.CoreProtocolPNames; ... request.config(CoreProtocolPNames.HTTP_CONTENT_CHARSET, Consts.UTF_8); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM