如何使用HttpPost发送日文字符

Com*_*02x 2 unicode encoding android http-post character-encoding

我正在尝试将日文字符发送到我的API服务器,但发送的字符是乱码并且变成了????.所以我使用以下方法将编码设置为实体:

    StringEntity stringEntity = new StringEntity(message, "UTF-8");
Run Code Online (Sandbox Code Playgroud)

但输出成了org.apache.http.entity.StringEntity@4316f850.我想知道是否转换stringEntity为字符串导致了这个,因为我想在我的服务器中发送它String.

这是我如何使用它:

public static String postSendMessage(String path, String message) throws Exception {
    DefaultHttpClient httpClient = new DefaultHttpClient();
    HttpConnectionParams.setConnectionTimeout(httpClient.getParams(), 10000); // Timeout limit
    HttpPost httpPost = new HttpPost(SystemInfo.getApiUrl() + path);
    List<NameValuePair> value = new ArrayList<NameValuePair>();

    StringEntity stringEntity = new StringEntity(message, "UTF-8");
    value.add(new BasicNameValuePair("message", stringEntity.toString())); //Here's where I converted the stringEntity to string

    UrlEncodedFormEntity entity = new UrlEncodedFormEntity(value);
    httpPost.setEntity(entity);
    HttpResponse httpResponse = httpClient.execute(httpPost);

    HttpEntity httpEntity = httpResponse.getEntity();
    InputStream is = httpEntity.getContent();

    String result = convertStreamToString(is);
    return result;
}
Run Code Online (Sandbox Code Playgroud)

哪里可能出错了?

Yui*_*aki 7

你不需要使用StringEntity.

List<NameValuePair> value = new ArrayList<NameValuePair>();
value.add(new BasicNameValuePair("message", message));
Run Code Online (Sandbox Code Playgroud)

相反,你必须传递第二个参数来初始化`UrlEncodedFormEntity.

UrlEncodedFormEntity entity = new UrlEncodedFormEntity(value, "UTF-8");
Run Code Online (Sandbox Code Playgroud)