2016-06-15 66 views
0

我試圖執行API並嘗試獲得json響應,但我得到"Disallowed Key Characters"的錯誤bf.readLine()json輸出中的「不允許的關鍵字符」錯誤

以下是我正在嘗試使用的代碼。但是當我在web瀏覽器中運行請求url時,我得到的響應沒有問題。但是通過使用java代碼,我無法提取數據。請幫助

String uri = "http://192.168.77.6/Ivr_ABN_API/?id?id=" 
      + mobile; 
    URL url; 
    Gson json = null; 
    try { 
     url = new URL(uri); 
     json = new Gson(); 

     HttpURLConnection connection; 
     access_token = db.getAccessTokenFromDB(); 
     connection = (HttpURLConnection) url.openConnection(); 
     connection.setRequestMethod("GET"); 

     System.out.println("URL:" + uri); 

     connection.setRequestProperty("Content-Type", "application/json"); 
     int status = connection.getResponseCode(); 
     resCode = Integer.toString(status); 


       InputStream in = connection.getInputStream(); 
       BufferedReader bf = new BufferedReader(
         new InputStreamReader(in)); 
       System.out.println("bf.readLine() - "+bf.readLine()); 

       while ((output = bf.readLine()) != null) { 
        JSONObject obj = new JSONObject(output); 
        System.out.println("output is "+output); 
        resCode = obj.getString("resCode"); 
        resDesc = obj.getString("COUNT"); 

       } 


     connection.disconnect(); 
+0

你沒有爲'InputStreamReader'指定一個字符集。 JSON通常使用UTF-8。另外,JSON不是面向行的,所以'readLine()'可能不是正確的方法。考慮使用'Gson.fromJson()'代替'Reader'作爲輸入。 –

+0

看看這個>> https://stackoverflow.com/questions/4964640/reading-inputstream-as-utf-8 –

回答

0

,因爲你需要添加編碼技術,通過該BufferedReader能夠編碼正確形式的任何特殊字符試試這個

BufferedReader in = new BufferedReader(new InputStreamReader(in, StandardCharsets.UTF_8)); 

代替

BufferedReader bf = new BufferedReader(new InputStreamReader(in)); 

希望這可能會幫助你。

謝謝。

0

我還發現了一個問題的解決方案和發佈供您參考。

HttpURLConnection connection; 
connection = (HttpURLConnection) url.openConnection(); 
     connection.setRequestMethod("GET"); 
connection.setRequestProperty("Accept", "application/json"); 
     connection.setRequestProperty("Content-Type", "application/json"); 
     int status = connection.getResponseCode(); 
BufferedReader bf = new BufferedReader(new InputStreamReader(
       connection.getInputStream())); 
相關問題