Apache-httpclient-aborting-a-request

提供:Dev Guides
移動先:案内検索

Apache HttpClient-リクエストの中止

  • abort()*メソッドを使用して現在のHTTPリクエストを中止できます。つまり、特定のリクエストでこのメソッドを呼び出した後、その実行は中止されます。

このメソッドが1回の実行後に呼び出された場合、その実行の応答は影響を受けず、後続の実行は中止されます。

次の例を見ると、HttpGetリクエストが作成され、* getMethod()*を使用してリクエスト形式が出力されています。

次に、同じリクエストで別の実行を実行しました。 もう一度1 ^ st ^実行を使用してステータス行を出力しました。 最後に、2回目の実行のステータス行を印刷しました。

説明したように、1 ^ st ^実行(アボートメソッド前の実行)の応答(アボートメソッドの後に書き込まれる2番目のステータス行を含む)が出力され、アボートメソッド後の現在のリクエストの後続の実行はすべて失敗します例外を呼び出します。

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.finddevguides.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.
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)