2017-10-13 120 views
0

我需要調用一個服務開始使用HTTP連接呼叫的HttpConnection,響應包含阿拉伯字符,但是當我把它用下面與編碼不工作

try { 

     HttpURLConnection conn = (HttpURLConnection) url.openConnection(); 
     conn.setRequestMethod("GET"); 

     InputStream in = new BufferedInputStream(conn.getInputStream()); 
     response = IOUtils.toString(in, "UTF-8"); 
    } catch (MalformedURLException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } catch (ProtocolException e) { 
     e.printStackTrace(); 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } 

代碼中的效應初探是

1|U|����� ������|$2|L|���� �������|$3|S|���� 

我試着不使用Commons-io也沒有工作

   HttpURLConnection connection = (HttpURLConnection) url.openConnection(); 
      connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); 
      connection.setConnectTimeout(5000); 
      connection.setRequestMethod("GET"); 
      connection.connect(); 
      int statusCode = connection.getResponseCode(); 
      //Log.e("statusCode", "" + statusCode); 
      if (statusCode == 200) { 
       sb = new StringBuilder(); 
       reader = new BufferedReader(new InputStreamReader(connection.getInputStream(),"UTF-8")); 

       char[] tmp = new char[1024]; 
       int l; 
       while((l = reader.read(tmp)) != -1) { 
        sb.append(tmp, 0, l); 
       } 
       //sb = buffer.toString(); 
      } 

      connection.disconnect(); 
      if (sb != null) 
       serverResponse = sb.toString(); 

另一種解決方案做我的東東D改變任何東西從網絡服務?但是當我從瀏覽器調用它時,所有字符都顯示清晰,沒有問題 有什麼建議?

回答

3

也許服務器沒有使用UTF-8,你的代碼試圖使用UTF-8解碼數據,但只有當服務器使用相同的編碼時才能工作。

瀏覽器可以正常工作,因爲它可能使用了HTTP頭「Content-Encoding」,它應該指出用於數據的編碼。

+0

謝謝youu完蛋了,我在Web服務的Web配置改變全球化爲UTF-8 – Amalo

1

請您解碼字符串響應

String dateStr = URLDecoder.decode(yourStringResponse, "utf-8");