HttpClient中止請求


可以使用abort()方法中止當前的HTTP請求,即在呼叫此方法之後,對特定請求執行它將中止。

如果在一次執行後呼叫此方法,則不會影響該執行的響應,並且將中止後續執行。

範例

如果觀察以下範例,可以看到建立了一個HttpGet請求,並列印了getMethod()使用的請求格式。

然後,使用相同的請求再一次執行。再次使用第一次執行列印狀態行。最後,列印第二次執行的狀態行。

如上所述,列印第一次執行(在中止方法之前執行)的響應(包括在中止方法之後寫入的第二個狀態行),並且在中止方法失敗後呼叫異常後當前請求的所有後續執行。

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;

public class HttpGetExample {
   public static void main(String args[]) throws Exception{

      //Creating an HttpClient object
      CloseableHttpClient httpclient = HttpClients.createDefault();

      //Creating an HttpGet object
      HttpGet httpget = new HttpGet("http://www.kaops.com/");

      //Printing the method used
      System.out.println(httpget.getMethod());

      //Executing the Get request
      HttpResponse httpresponse = httpclient.execute(httpget);

      //Printing the status line
      System.out.println(httpresponse.getStatusLine());

      httpget.abort();
      System.out.println(httpresponse.getEntity().getContentLength());

      //Executing the Get request
      HttpResponse httpresponse2 = httpclient.execute(httpget);
      System.out.println(httpresponse2.getStatusLine());
   }
}

執行上面範例程式碼,得到以下結果 -

On executing, the above program generates the following output.
GET
HTTP/1.1 200 OK
-1
Exception in thread "main" org.apache.http.impl.execchain.RequestAbortedException:
Request aborted
at org.apache.http.impl.execchain.MainClientExec.execute(MainClientExec.java:180)
at org.apache.http.impl.execchain.ProtocolExec.execute(ProtocolExec.java:185)
at org.apache.http.impl.execchain.RetryExec.execute(RetryExec.java:89)
at org.apache.http.impl.execchain.RedirectExec.execute(RedirectExec.java:110)
at org.apache.http.impl.client.InternalHttpClient.doExecute(InternalHttpClient.java:185)
at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:83)
at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:108)
at HttpGetExample.main(HttpGetExample.java:32)