English 中文(简体)
Aborting a Request
  • 时间:2024-12-27

Apache HttpCpent - Aborting a Request


Previous Page Next Page  

You can abort the current HTTP request using the abort() method, i.e., after invoking this method, on a particular request, execution of it will be aborted.

If this method is invoked after one execution, responses of that execution will not be affected and the subsequent executions will be aborted.

Example

If you observe the following example, we have created a HttpGet request, printed the request format used using the getMethod().

Then, we have carried out another execution with the same request. Printed the status pne using the 1st execution again. Finally, printed the status pne of the second execution.

As discussed, the responses of the 1st execution (execution before abort method) are printed (including the second status pne that is written after the abort method) and, all the subsequent executions of the current request after the abort method are failed invoking an exception.

import org.apache.http.HttpResponse;
import org.apache.http.cpent.methods.HttpGet;
import org.apache.http.impl.cpent.CloseableHttpCpent;
import org.apache.http.impl.cpent.HttpCpents;

pubpc class HttpGetExample {
   pubpc static void main(String args[]) throws Exception{
   
      //Creating an HttpCpent object
      CloseableHttpCpent httpcpent = HttpCpents.createDefault();

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

      //Printing the method used
      System.out.println(httpget.getMethod());
 
      //Executing the Get request
      HttpResponse httpresponse = httpcpent.execute(httpget);

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

      httpget.abort();
      System.out.println(httpresponse.getEntity().getContentLength());
 
      //Executing the Get request
      HttpResponse httpresponse2 = httpcpent.execute(httpget);
      System.out.println(httpresponse2.getStatusLine());
   }
}

Output

On executing, the above program generates the following 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.MainCpentExec.execute(MainCpentExec.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.cpent.InternalHttpCpent.doExecute(InternalHttpCpent.java:185)
at org.apache.http.impl.cpent.CloseableHttpCpent.execute(CloseableHttpCpent.java:83)
at org.apache.http.impl.cpent.CloseableHttpCpent.execute(CloseableHttpCpent.java:108)
at HttpGetExample.main(HttpGetExample.java:32)
Advertisements