如何使用Apache HttpClient在Post请求中编码俄语文本?

7

以下是Java代码:

    public static void register(UserInfo info) throws ClientProtocolException, IOException, JSONException, RegistrationException {
        List<NameValuePair> params=new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair("name", info.getName()));
        params.add(new BasicNameValuePair("email", info.getEmail()));
        params.add(new BasicNameValuePair("pass", info.getPassword()));
        params.add(new BasicNameValuePair("genus", String.valueOf(info.getGenus())));
        String response=doPostRequest(params, REGISTRATION_URL);
    }

private static String doPostRequest(List<NameValuePair> params, String url) throws ClientProtocolException, IOException {
    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost(url);

    httppost.setEntity(new UrlEncodedFormEntity(params));
    HttpResponse response = httpclient.execute(httppost); 

    return getContentFromInputStream(response.getEntity().getContent());
} 

private static String getContentFromInputStream(InputStream is) throws IOException {
    String line;
    StringBuilder sb=new StringBuilder();
    BufferedReader reader=new BufferedReader(new InputStreamReader(is));
    while((line=reader.readLine())!=null) {
        sb.append(line);
    }
    reader.close();
    return sb.toString();
}

如上所示,我发送了POST请求并获取到响应。但是,在注册方法中,我使用了俄语名称(西里尔字母),服务器上出现了“????? ???”。我该如何解决这个问题?如何对俄文进行编码?

你传递什么作为你的内容类型?使用了什么字符集? - fge
你使用哪个服务器? - Menelaos
6个回答

11

您需要将请求编码设置为UTF-8。

The request or response body can be any encoding, but by default is ISO-8859-1. The encoding may be specified in the Content-Type header, for example:
Content-Type: text/html; charset=UTF-8

从:http://hc.apache.org/httpclient-3.x/charencodings.html

这是一个实现的例子:

HttpClient httpclient = new HttpClient();
httpclient.getParams().setParameter("http.protocol.version", HttpVersion.HTTP_1_1);
httpclient.getParams().setParameter("http.protocol.content-charset", "UTF-8");

此外,我看到你正在使用 UrlEncodedFormEntity。你应该在构造函数中添加编码,如下所示:

new UrlEncodedFormEntity(nameValuePairs,"UTF-8");

有用的链接:https://dev59.com/4m435IYBdhLWcg3wtCOQ 。同时,请确保服务器也能够读取UTF-8编码。 - Menelaos

3
你应该尝试对参数进行编码。
URLEncoder.encode(URL, "UTF-8");

0

httpclient.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "UTF-8");


请解释您的答案。 - Gwenc37

0

也许您正在错误地阅读或编写响应?

请确保在编写请求读取请求以及post http headers中使用相同的编码。

要为读取数据定义编码,请使用InputStreamReader(InputStream, Charset)构造函数。


0
如果你已经厌倦了不断寻找正确的头文件/编码组合,那么你可以将字符串编码为URI格式并解码回来,这样就可以保留任何非ASCII字符。
String cyrillicString = "ыыыыыы";

//encode string into URI format
String transportString = URLEncoder.encode(cyrillicString, "UTF-8");

//transport string somewhere 

//decode back
String decodedString = URLDecoder.decode(transportString, "UTF-8");

0

如果您以json格式发布:

  1. 创建客户端
HttpClientBuilder clientBuilder = HttpClients.custom();
//add header with charset UTF-8
clientBuilder.setDefaultHeaders(Arrays.asList(new BasicHeader(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON.getMimeType()))); //application/json;charset=UTF-8
CloseableHttpClient httpClient = clientBuilder.build();
  • 创建 HttpPost
  • HttpPost post = new HttpPost("/hostIp:port/forexample/saveMyObject");
    
  • 将对象写成字符串(String)
  • PostRequestExample request = new PostRequestExample();
    request.setUsername("userName");
    request.setUserAge(98));
    
    ObjectMapper objectMapper = new ObjectMapper(); //import com.fasterxml.jackson.databind
    //ContentType.APPLICATION_JSON - encode russian symbols as UTF8
    post.setEntity(new StringEntity(objectMapper.writeValueAsString(request), ContentType.APPLICATION_JSON));
    
    1. 执行
    CloseableHttpResponse response = httpClient.execute(post);
    

    网页内容由stack overflow 提供, 点击上面的
    可以查看英文原文,
    原文链接