本文介绍了如何使用Apache HttpClient在Post请求中编码俄语文本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有以下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请求并获得响应.但是在登录方法上我使用俄语名称(西里尔字母),并且有"???????????"在我的服务器上.我该如何解决?如何编码俄语文本?

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?

推荐答案

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

You need to set your request encoding to 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

如何完成此操作的示例:

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");

此外,我看到您正在使用UrlEncodedFormEntity.您应该这样向构造函数添加编码:

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

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

这篇关于如何使用Apache HttpClient在Post请求中编码俄语文本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-20 11:41