gromit190:
私はHttpClientをを使用しているとき、私は特定の要求をリダイレクトを無効にする方法を知っていただきたいと思います。今、私のクライアントは、どちらかのすべての要求を可能または無効リダイレクト。私はすべて同じクライアントで、いくつかのリダイレクトと要求したが、リダイレクトを無効にして、いくつかを作ることができるようにしたいです。出来ますか?
2つのクライアントを使用しての例(これは私は避けたいものです):
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
public class MyClass {
public static void main(String[] args) throws Exception {
// Redirected client
CloseableHttpClient client = HttpClients.createDefault();
HttpGet get = new HttpGet("http://www.google.com");
client.execute(get);
// Non-redirected client
CloseableHttpClient client2 = HttpClientBuilder.create().disableRedirectHandling().build();
HttpGet get2 = new HttpGet("http://www.google.com");
client2.execute(get2);
}
}
Mirdm:
あなた自身を実装することができますRedirectStrategy
あなたが望むようリダイレクトを処理するために、使用するsetRedirectStrategy
のHttpClientBuilder
HTTPクライアントがリダイレクト戦略を使ってみましょうします。
あなたは確認することができDefaultRedirectStrategyとLaxRedirectStrategy参照の実装を。
重要な部分はあるisRedirected
の方法RedirectStrategy
。あなたは返す必要がtrue
またはfalse
あなたが特定の要求かどうかをリダイレクトしたい場合は異なります。HTTPリクエストエグゼキュータは呼び出しされる実際のリダイレクトを行う前に、このメソッドを。
たとえば、あなたが拡張することができますDefaultRedirectStrategy
し、上書きするisRedirected
方法を
...
public class MyRedirectStrategy extends DefaultRedirectStrategy {
...
@Override
public boolean isRedirected(
final HttpRequest request,
final HttpResponse response,
final HttpContext context) throws ProtocolException {
// check request and return true or false to redirect or not
...
}
}