Apache 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("https://tutorialspoint.tw/");

      //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)
廣告
© . All rights reserved.