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.zyiz.net/"); //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)
上一篇:HttpClient关闭连接
下一篇:HttpClient拦截器
关注微信小程序
扫描二维码
程序员编程王