2011-01-07 51 views
2

我正在調用一個返回XML的其餘WS。一些元素的字符串包含像áãç等特殊字符... 當我通過瀏覽器獲取信息時,所有顯示都正確,但是從Android中調用它時,我沒有得到正確的特殊字符。UTF8在調用REST webservice時在Android中進行編碼

注意「解碼」和「編碼」變量:

當我使用 URLDecoder.decode(result, "UTF-8") 結果保持不變

當我使用 URLEncoder.encode(result, "UTF-8")結果將更改爲它可以預期(全%的符號和數字代表符號和特殊字符)。

下面是調用web服務的方法:

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(); 
} 

任何幫助,將不勝感激

回答

12

使用此得到XML字符串,假設服務器在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); 
+0

爲我工作,謝謝! – baekacaek 2013-09-04 20:54:51

2

呃。 URLDecoder和編碼器用於編碼和解碼URL,而不是XML內容。它用於提出請求時使用的URL。所以代碼只是......錯了。

但更大的問題是您正在接受一個字符串,而內容真的是需要解析的XML。爲了解析器對UTF-8進行正確的解碼(以及處理實體等),你最好從請求中獲取一個字節[],並將其傳遞給解析器;雖然要求http客戶端解碼可能工作正常(假設服務正確表示使用的編碼;並不是所有的 - 但即使不是,XML解析器可以從xml聲明中找出它)。

所以:刪除URLDecoder/URLEncoder的東西,解析器的XML,並從XML中提取你想要的數據。