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

时间:2013-06-10 12:49:06

标签: java httpclient

有以下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请求并获得响应。但在注册方法我使用俄语名称(西里尔文),并有“????? ???”在我的服务器上。我该如何解决?我如何编码俄文?

6 个答案:

答案 0 :(得分: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");

答案 1 :(得分:2)

你应该尝试编码参数

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

答案 2 :(得分:0)

也许您正在阅读或撰写错误的回复?

确保在撰写请求阅读以及发布http标头中使用相同的编码。

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

答案 3 :(得分:0)

httpclient.getParams()。setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET,&#34; UTF-8&#34;);

答案 4 :(得分: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");

答案 5 :(得分: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();
  1. 创建HttpPost
HttpPost post = new HttpPost("/hostIp:port/forexample/saveMyObject");
  1. 将对象写为字符串(字符串)
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);