新彩天欢迎您!
幻海优品

Apache HttpClient - 中止请求

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

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

示例

如果您观察以下示例,我们创建了一个HttpGet请求,打印了使用 getMethod()使用的请求格式.

然后,我们进行了使用相同的请求执行另一个执行.再次使用1 st 执行打印状态行.最后,打印第二次执行的状态行.

如上所述,打印1 st 执行(在中止方法之前执行)的响应(包括在中止方法之后写入的第二个状态行),并且在中止方法之后当前请求的所有后续执行都无法调用异常.

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.IT屋.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.GETHTTP/1.1 200 OK-1Exception in thread "main" org.apache.http.impl.execchain.RequestAbortedException:Request abortedat 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)

免责声明:以上内容(如有图片或视频亦包括在内)有转载其他网站资源,如有侵权请联系删除