2015-07-19 130 views
0

我需要對包含JSON數據的url進行GET請求,並嘗試使用Loopj庫,但它不返回任何內容。我試圖找到互聯網上的例子,但他們證明,也許,是過時的(onSuccess方法有不同的參數)。我想我的代碼適應那個例子,我得到了什麼:android-GET請求與Loopj

String AllData=""; AsyncHttpClient client = new AsyncHttpClient(); 
    client.get("wantedUrl", new AsyncHttpResponseHandler() { 
     @Override 
     public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) { 
      for (byte aResponseBody : responseBody) { 
       AllData += aResponseBody; 
      } 

     } 
     @Override 
     public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) { 
      Toast.makeText(getApplicationContext(),"We got an error",Toast.LENGTH_SHORT).show(); 
     } 
    }); 

「wantedUrl」是使用JSON的網址,但「ALLDATA」保持爲空。如何解決它?

回答

0

你得到AsyncHttpResponseHandler回調你需要JsonHttpResponseHandler。使用下面的代碼來讓事情順利進行。

String AllData=""; AsyncHttpClient client = new AsyncHttpClient(); 
     client.get("wantedUrl", new JsonHttpResponseHandler(){ 
      @Override 
      public void onSuccess(int statusCode, Header[] headers, JSONArray response) { 
       super.onSuccess(statusCode, headers, response); 

       //Here response will be received in form of JSONArray 
      } 

      @Override 
      public void onSuccess(int statusCode, Header[] headers, JSONObject response) { 
       super.onSuccess(statusCode, headers, response); 

       //Here response will be received in form of JSONObject 
      } 

      @Override 
      public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) { 
       super.onFailure(statusCode, headers, responseString, throwable); 
       Toast.makeText(getApplicationContext(), "We got an error", Toast.LENGTH_SHORT).show(); 
      } 
     }); 
+0

它的工作原理,但如何將響應記錄到活動類的變量? (我聲明它是一個「公共靜態」來訪問它的onSuccess方法,但在上述構造之外它有它以前的價值(但在onSuccess一切都很好 - 我用相同的吐司測試它) –

+0

@JustinMcGuire你需要學習JAVA的基本概念沒有攻擊 –

+0

我知道我有點新手,但無論如何,我需要將響應數據記錄到數組中以擴充ListView - 那麼我能做到這一點的方式是什麼? –