我正在尝试将日文字符发送到我的API服务器,但发送的字符出现乱码并变为????
。所以我使用以下命令将编码设置为实体:
StringEntity stringEntity = new StringEntity(message, "UTF-8");
但输出变为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;
}
我哪里可能出错?
答案 0 :(得分:7)
您无需使用StringEntity
。
List<NameValuePair> value = new ArrayList<NameValuePair>();
value.add(new BasicNameValuePair("message", message));
相反,你必须传递第二个参数来初始化`UrlEncodedFormEntity。
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(value, "UTF-8");