1

我正在做一个项目,我需要从我的应用引擎服务器获取一些包含希伯来字符的数据(数据以 json 格式发送)。

在服务器端:

resp.setHeader("Content-Type", "application/json; charset=UTF-8");
PrintWriter out = resp.getWriter();
out.print(responeData.toString());

当我调试服务器时,我看到响应数据似乎很好(意思是,它显示了我的希伯来语字符。

在客户端(安卓):

执行此代码后,我得到的结果数据是 ??? 而是希伯来字符。我尝试了所有不同的编码,例如'windows-1255'、'iso-8859-8' 有谁知道问题出在哪里?谢谢!

// Create new default http client
    HttpClient client = new DefaultHttpClient();
    HttpConnectionParams.setConnectionTimeout(client.getParams(), 10000); // Timeout Limit
    HttpConnectionParams.setSoTimeout(client.getParams(), 10000);
    HttpResponse response;
    HttpPost post = new HttpPost(serviceURL);

    try {
        StringEntity se = new StringEntity(requestPayload.toString());
        post.addHeader(CustomHeader.TASK_NAME.getHeaderName(), taskName);
        se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
        post.setEntity(se);

        // Execute the request
        response = client.execute(post);

        // Get the response status code
        StatusLine statusLine = response.getStatusLine();
        int statusCode = statusLine.getStatusCode();

        if (statusCode == 200) { // Ok
            if (response != null) { // Checking response
                InputStream in = response.getEntity().getContent(); // Get the data in the entity
                retreturnVal = HttpCaller.readContentFromIS(in);
            }
        }
    } catch (Exception e) {
        Log.e("Error in connectivity layer, stacktrace: ", e.toString());
        return null;
    }

    public static String readContentFromIS(InputStream in) throws IOException {
    BufferedReader reader = new BufferedReader(
            new InputStreamReader(in, "UTF-8"), 8);
    StringBuffer sb = new StringBuffer();
    String line = "";
    while ((line = reader.readLine()) != null) {
        sb.append(line + "\n");
    }
    return sb.toString();       
}
4

2 回答 2

2

假设您在服务器上使用 a ServletResponse,而不是调用

resp.setHeader("Content-Type", "application/json; charset=UTF-8");

你应该打电话

resp.setContentType("application/json; charset=UTF-8");

这应该具有将调用中使用的编码更改getWriter()为 UTF-8 的效果。我不认为打电话setHeader有同样的副作用。

于 2012-08-19T01:36:23.200 回答
0

我有同样的问题,但我做到了

 StringEntity se = new StringEntity(requestPayload.toString(), "UTF-8");

代替

 StringEntity se = new StringEntity(requestPayload.toString());

它对我来说很好,这是另一种解决方案。

于 2012-09-07T17:54:43.793 回答