Apache Httpclient 简明教程

Apache HttpClient - Aborting a Request

你可以使用 abort() 方法中止当前的 HTTP 请求,即在对特定请求调用此方法后,将中止其执行。

如果在一次执行后调用此方法,则该执行的响应不会受到影响,后续执行将被中止。

Example

如果你看到以下示例,我们创建了一个 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://www.tutorialspoint.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());
   }
}

Output

执行后,上述程序会生成以下输出−

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)