HttpClientをを使用して、同じクライアントとの具体的な要求のために無効にリダイレクト

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あなたが望むようリダイレクトを処理するために、使用するsetRedirectStrategyHttpClientBuilderHTTPクライアントがリダイレクト戦略を使ってみましょうします。

あなたは確認することができDefaultRedirectStrategyLaxRedirectStrategy参照の実装を。

重要な部分はある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
    ...
    }
}

おすすめ

転載: http://43.154.161.224:23101/article/api/json?id=172053&siteId=1