2017-05-27 38 views
0

您好我正在嘗試爲學校項目創建一個Android應用程序,該應用程序創建一個包含在Google工作表中的一些數據的接口。 我在嘗試檢索其json字符串時遇到問題,並通過緩衝區將其轉換爲字符串,問題是執行此操作的標準方式無效。 下面是我使用的檢索數據到我連接我得到的代碼,鏈接,和日誌,當我運行它:https://script.googleusercontent.com/macros/echo?user_content_key=YUm908_F4USanZMXYLM5SSNopIaGpE9lsPLN4Gd76Ev-ps1HtglllhSfOon8LijwbaCtE5yErItehXcvQml5MHPUIoB-gnlVOJmA1Yb3SEsKFZqtv3DaNYcMrmhZHmUMWojr9NvTBuBLhyHCd5hHa1ZsYSbt7G4nMhEEDL32U4DxjO7V7yvmJPXJTBuCiTGh3rUPjpYM_V0PJJG7TIaKp6DlhKiyTgeD37GVXNPmWi9BLr90SAXNavw2PD7IFU7Gool08_D5VdRirKpWCIA4qy6ynGhL6kv9iPAz3iOzAmo&lib=MbpKbbfePtAVndrs259dhPT7ROjQYJ8yx從谷歌電子表格中獲取JSON

public class JSONTask { 
 
    private String txtJson=null; 
 

 
    public String JSONTask(URL url){ 
 
     HttpURLConnection connection= null; 
 
     BufferedReader reader = null; 
 

 
     Log.v("JSONTAKS","READY TO GET JSON"); 
 
     Log.v("JSONTAKS URL",url.toString()); 
 

 
     try{ 
 
      connection=(HttpURLConnection) url.openConnection(); 
 
      connection.connect(); 
 
      Log.v("JSONTask","READY TO BUFFER"); 
 

 
      InputStream stream=connection.getInputStream(); 
 
      reader =new BufferedReader(new InputStreamReader(stream)); 
 

 
      StringBuffer buffer = new StringBuffer(); 
 
      String line=""; 
 
      Log.v("JSONTask",stream.toString()); 
 

 
      while((line = reader.readLine())!=null){ 
 
       buffer.append(line+"\n"); 
 
       Log.v("JSONTASK", buffer.toString()); 
 

 
      } 
 
      Log.v("JSONTASK txt",buffer.toString()); 
 
      txtJson=buffer.toString(); 
 
      Log.v("JSONTASK txt",txtJson); 
 

 
     }catch(Exception e){ 
 
      e.printStackTrace(); 
 
      Log.v("EXCEPTION", "EXCEPTION THROWN"); 
 
     }finally { 
 
      if(connection!=null){ 
 
       connection.disconnect(); 
 
      } 
 
     }try{ 
 
      if(reader!=null){ 
 
       reader.close(); 
 
      } 
 
     }catch (Exception e){ 
 
      e.printStackTrace(); 
 
     } 
 

 

 
     return txtJson; 
 
    }

https://i.stack.imgur.com/p99eR.png

回答

1

強烈建議在Android上使用現有的庫。如果有,爲什麼你寫你自己的方法來REST沒有具體的原因,你應該檢查出http://square.github.io/okhttp/

您需要檢索的代碼在網站上:

OkHttpClient client = new OkHttpClient(); 

    String run(String url) throws IOException { 
     Request request = new Request.Builder() 
     .url(url) 
     .build(); 

     Response response = client.newCall(request).execute(); 
     return response.body().string(); 
    } 
+0

哇,謝謝!像魅力一樣工作;)我試圖不使用庫來獲得代碼的一些練習,但是你爲這個庫節省了很多時間。 –