2017-08-09 67 views
0

我想知道是否有可能阻止代碼的執行在HTTP請求示例的responseReceived:的Android停止執行

new HttpRequest() { 
     @Override 
     public void onResponseReceived(JSONObject result) { 
     // doing a lot of thing 
     } 
}.get("http://niceUrl"); 

的onResponseReceived裏面我做了很多的事情(解析JSON,將數據添加到列表,等等。)

當我調用這個函數:

private void stopExecutionOfOnResponseReceived(){ 
    // I would like to stop the previous HttpRequest and launch a new One 
} 

HttpRequest中是誰繼承抽象類擴展的AsyncTask字符串,沃伊d,JSONObject

+0

asynctask類有方法'cancel()'檢查 –

+0

如果你可以調用cancel方法,你不能阻止它。 – redAllocator

回答

1

您可以使用中止方法。 本示例演示如何在正常完成之前中止HTTP方法。

public class ClientAbortMethod { 

    public final static void main(String[] args) throws Exception { 
     CloseableHttpClient httpclient = HttpClients.createDefault(); 
     try { 
      HttpGet httpget = new HttpGet("http://httpbin.org/get"); 

      System.out.println("Executing request " + httpget.getURI()); 
      CloseableHttpResponse response = httpclient.execute(httpget); 
      try { 
       System.out.println("----------------------------------------"); 
       System.out.println(response.getStatusLine()); 
       // Do not feel like reading the response body 
       // Call abort on the request object 
       httpget.abort(); 
      } finally { 
       response.close(); 
      } 
     } finally { 
      httpclient.close(); 
     } 
    } 

} 
+0

我不知道這是否有用,因爲我使用HttpUrlConnection作爲請求 – Vodet