3

How do I set the character encoding in Apache HTTP Components?

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. http components converts them to latin-1 when I tested. I want it to convert to something else (e.g., utf-8).

4

1 回答 1

10

按照您在示例中显示的内容,您似乎正在使用流利的 API。

查看javadocs有一个request.bodyForm()接受字符集的版本:

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

根据来源,字符集默认为Consts.ISO_8859_1(aka Latin-1)。

备择方案

  1. 如果这不起作用,请考虑:

    import org.apache.http.Consts;
    ...
    request.elementCharset(Consts.UTF_8);
    
  2. 作为最后的手段,应该可以设置内容字符集。查看源代码elementCharset(),您可以尝试以下操作:

    import org.apache.http.Consts;
    import org.apache.http.params.CoreProtocolPNames;
    ...
    request.config(CoreProtocolPNames.HTTP_CONTENT_CHARSET, Consts.UTF_8);
    
于 2013-01-24T00:11:39.943 回答