使用 HttpClient 将带有 post 方法的 utf8 内容发送到 android 中的服务器

Posted

技术标签:

【中文标题】使用 HttpClient 将带有 post 方法的 utf8 内容发送到 android 中的服务器【英文标题】:Sending utf8 contents with post method to server in android using HttpClient 【发布时间】:2012-01-22 20:12:07 【问题描述】:

这是我的示例代码,但是我使用了 HttpProtocolParams.setContentCharset(params, "utf-8");我是我的代码,但是当我发送 utf-8 数据时,我只收到“?????”在服务器端(php 代码)!有什么问题?

    HttpParams params = new BasicHttpParams();
    HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setContentCharset(params, "utf-8");

    HttpClient httpclient = new DefaultHttpClient(params);

    httpclient.getParams().setParameter("http.protocol.content-charset", "UTF-8");
    HttpPost httppost = new HttpPost("URL_TO_SERVER");

    try 

        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
        nameValuePairs.add(new BasicNameValuePair("uname", name.getText().toString()));
        nameValuePairs.add(new BasicNameValuePair("uemail", email.getText().toString()));
        nameValuePairs.add(new BasicNameValuePair("udesc", body.getText().toString()));
        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

        HttpResponse hresponse = httpclient.execute(httppost);

        String response = new Scanner(hresponse.getEntity().getContent(), "UTF-8").useDelimiter("\\A").next();

        hresponse.getEntity().consumeContent();
        httpclient.getConnectionManager().shutdown();

        Log.d("WX", response.toString());
        Toast.makeText(getApplicationContext(), response, Toast.LENGTH_LONG).show();

     catch (ClientProtocolException e) 
        // TODO Auto-generated catch block
     catch (IOException e) 
        // TODO Auto-generated catch block
    

【问题讨论】:

【参考方案1】:

也许您应该为实体使用 UTF-8:

httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs,"UTF-8"));

【讨论】:

【参考方案2】:

我工作过

public static String sendData(String data) 
    String str = null;
    HttpClient client = new DefaultHttpClient();
    HttpPost httppost = new HttpPost(serverurl);
    try 
        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
        nameValuePairs.add(new BasicNameValuePair("s", data));
        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
        HttpResponse response = client.execute(httppost);
        str = new Scanner(response.getEntity().getContent(), "UTF-8").useDelimiter("\\A").next();

        Log.v("srv response:", str);
     catch (SecurityException e) 
        str = "err2";
     catch (IOException error) 
        str = "err1.1";
     catch (NullPointerException e) 
        str = "err1.2";
    
    return str;

【讨论】:

以上是关于使用 HttpClient 将带有 post 方法的 utf8 内容发送到 android 中的服务器的主要内容,如果未能解决你的问题,请参考以下文章

带有客户端证书的 HttpClient POST 请求

带有标头和正文的 HTTPClient 发布请求

C#:带有 POST 参数的 HttpClient

使用 POST 方法将 HttpWebRequest 转换为 HttpClient

在 Android 中使用带有 post 参数的 HttpClient 和 HttpPost

带有自定义标头的 C# HttpClient POST 请求发送不正确的 Content-Type 标头字段