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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17024268/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-01 00:44:52  来源:igfitidea点击:

How to encode russian text in Post request using Apache HttpClient?

javahttpclient

提问by user2218845

There is the following Java code:

有以下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();
}

As you can see above, I send POST request and get response. But in register method I use russian name (cyrillic), and there is "????? ???" on my server. How can I fix it? How can I encode russian text?

正如您在上面看到的,我发送 POST 请求并获得响应。但是在注册方法中,我使用俄语名称(西里尔文),并且有“??????? ???” 在我的服务器上。我该如何解决?我如何编码俄语文本?

回答by Menios

You need to set your request encoding to UTF-8.

您需要将请求编码设置为 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

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

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

An example of how this is accomplished:

这是如何实现的一个例子:

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

Additionally, I see your using UrlEncodedFormEntity. You should add encoding to the constructor as so:

此外,我看到您使用UrlEncodedFormEntity. 您应该向构造函数添加编码,如下所示:

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

回答by shreyansh jogi

you should try encoding parameters

你应该尝试编码参数

URLEncoder.encode(URL, "UTF-8");

回答by larryhu

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

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

回答by HymanHammer

If you tired of searching for correct headers / encoding combinations, you can encode string to URI format and decode back, this will preserve any non-ascii chars

如果您厌倦了搜索正确的标头/编码组合,您可以将字符串编码为 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");

回答by pavel.kh

If you post as json:

如果您以 json 的形式发布:

  1. Create client
  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();
  1. Create HttpPost
  1. 创建 HttpPost
HttpPost post = new HttpPost("/hostIp:port/forexample/saveMyObject");
  1. Write object as string (String)
  1. 将对象写为字符串(String)
PostRequestExample request = new PostRequestExample();
request.setUsername("userName");
request.setUserAge(98));

ObjectMapper objectMapper = new ObjectMapper(); //import com.fasterxml.Hymanson.databind
//ContentType.APPLICATION_JSON - encode russian symbols as UTF8
post.setEntity(new StringEntity(objectMapper.writeValueAsString(request), ContentType.APPLICATION_JSON));
  1. execute
  1. 执行
CloseableHttpResponse response = httpClient.execute(post);

回答by Dariusz

Perhaps you are reading or writing the response wrong?

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

Make sure you use the same encoding in both writing the requestand reading itand in the post http headers.

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

To define encoding for read data use InputStreamReader(InputStream, Charset)constructor.

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