调用REST Web服务时,UTF8编码在Android中Web、REST、Android

2023-09-06 01:23:27 作者:oO冰暴★战神Oo

我调用一个休息WS返回XML。有些元素具有字符串包含特殊字符,如AAC等... 当我通过浏览器获取信息,这一切是正常显示,但是从Android的调用时,我没有得到适当的特殊字符。

I'm invoking a rest WS that returns XML. Some elements have strings include special characters like áãç etc... When I get the information via browser all of it is shown properly but when invoking it from Android I don't get the proper special characters.

请注意,去codeD和EN codeD'变量:

Notice the 'decoded' and 'encoded' variables:

当我使用 URLDe coder.de code(结果,UTF-8) 结果保持不变

when I use URLDecoder.decode(result, "UTF-8") The result stays the same

当我使用 URLEn coder.en code(结果,UTF-8)的结果将更改为它可以预期(满%的符号和数字再presenting符号和特殊字符)。

when I use URLEncoder.encode(result, "UTF-8") The result changes to what it would be expected (full of %'s symbols and numeric representing symbols and special characters).

下面是调用Web服务的方法:

Here's the method to call the webservice:

public void updateDatabaseFromWebservice(){

    // get data from webservice
    Log.i(TAG, "Obtaining categories from webservice");

    HttpClient client = new DefaultHttpClient();
    HttpGet request = new HttpGet(ConnectionProperties.CATEGORIES_URI);

    ResponseHandler<String> handler = new BasicResponseHandler();

    String result = "";
    String decoded;
    String encoded;
    try {                   
        result = client.execute(request, handler);  

        decoded = URLDecoder.decode(result, "UTF-8");
        encoded = URLEncoder.encode(result, "UTF-8");
        String c = "AS";

    } catch (Exception e) {  
        Log.e(TAG, "An error occurred while obtaining categories", e);
    }

    client.getConnectionManager().shutdown();
}

任何帮助将AP preciated

Any help would be appreciated

推荐答案

使用它来获取XML字符串,假设服务器连接codeS数据以UTF-8:

Use this to get xml string, assuming the server encodes data in UTF-8:

HttpResponse response = client.execute(request);
... // probably some other code to check for HTTP response status code
HttpEntity responseEntity = response.getEntity();
String xml = EntityUtils.toString(responseEntity, HTTP.UTF_8);