【问题标题】:How to send Japanese characters using HttpPost如何使用 HttpPost 发送日文字符
【发布时间】:2014-02-22 04:43:25
【问题描述】:

我正在尝试将日文字符发送到我的 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;
}

我哪里出错了?

【问题讨论】:

    标签: android unicode encoding character-encoding http-post


    【解决方案1】:

    你不需要使用StringEntity

    List<NameValuePair> value = new ArrayList<NameValuePair>();
    value.add(new BasicNameValuePair("message", message));
    

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

    UrlEncodedFormEntity entity = new UrlEncodedFormEntity(value, "UTF-8");
    

    【讨论】:

    • 谢谢,我的服务器现在已经接受了这些字符。不过,我有相关的问题,在我的应用程序中,我无法下载具有日语文件名的文件,例如名为 - ははは.pdf 的 PDF。有没有办法设置下载的编码? Here 是代码。
    • @CompaqLE2202x:您没有显示您从哪里获得urlpdfFilename,但通常url 作为URI 必须是纯ASCII。如果您有一个包含非 ASCII 字符的 IRI,则需要先将其转换为 URI;对于通过对字符的 UTF-8 字节进行 % 编码来完成的路径部分。 URLEncoder.encode(filename, "UTF-8") 几乎可以做到这一点(除了空格错误,你可以用 %20 替换 + 来解决这个问题)。
    • @bobince 其实pdfFileName只是文件名加后缀,url是path[0],比如(http://192.168.xx.xx/resources/upload/pdf/ははは.pdf)。但是当我将它粘贴到浏览器中时,它变成了(http://192.168.xx.xx/resources/upload/pdf/%E3%81%AF%E3%81%AF%E3%81%AF.pdf)。正如你所说,我将path[0] 转换为URI,然后转换为URL,但后来什么也没发生。我也试过String urlEncoded = URLEncoder.encode(path[0], "UTF-8");,但触发了Protocol not found。能多指教一下吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-18
    • 1970-01-01
    • 1970-01-01
    • 2011-12-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多