下面列出了怎么用org.apache.http.impl.client.DefaultRedirectStrategy的API类实例代码及写法,或者点击链接到github查看源代码。
public RequestEntityRestStorageService(final S3Session session, final HttpClientBuilder configuration) {
super(null, new PreferencesUseragentProvider().get(), null, toProperties(session.getHost(), session.getSignatureVersion()));
this.session = session;
this.properties = this.getJetS3tProperties();
// Client configuration
configuration.disableContentCompression();
configuration.setRetryHandler(new S3HttpRequestRetryHandler(this, preferences.getInteger("http.connections.retry")));
configuration.setRedirectStrategy(new DefaultRedirectStrategy() {
@Override
public HttpUriRequest getRedirect(final HttpRequest request, final HttpResponse response, final HttpContext context) throws ProtocolException {
if(response.containsHeader("x-amz-bucket-region")) {
final String host = ((HttpUriRequest) request).getURI().getHost();
if(!StringUtils.equals(session.getHost().getHostname(), host)) {
regionEndpointCache.putRegionForBucketName(
StringUtils.split(StringUtils.removeEnd(((HttpUriRequest) request).getURI().getHost(), session.getHost().getHostname()), ".")[0],
response.getFirstHeader("x-amz-bucket-region").getValue());
}
}
return super.getRedirect(request, response, context);
}
});
this.setHttpClient(configuration.build());
}
private HttpAsyncClientBuilder setRedirects(HttpAsyncClientBuilder clientBuilder) {
clientBuilder.setRedirectStrategy(new DefaultRedirectStrategy() {
/** Redirectable methods. */
private String[] REDIRECT_METHODS = new String[] {
HttpGet.METHOD_NAME, HttpPost.METHOD_NAME,
HttpPut.METHOD_NAME, HttpDelete.METHOD_NAME, HttpHead.METHOD_NAME
};
@Override
protected boolean isRedirectable(String method) {
for (String m : REDIRECT_METHODS) {
if (m.equalsIgnoreCase(method)) {
return true;
}
}
return false;
}
});
return clientBuilder;
}
@Test
public final void givenRedirectingPOSTViaPost4_2Api_whenConsumingUrlWhichRedirectsWithPOST_thenRedirected() throws IOException {
final CloseableHttpClient client = HttpClients.custom().setRedirectStrategy(new DefaultRedirectStrategy() {
/** Redirectable methods. */
private final String[] REDIRECT_METHODS = new String[]{HttpGet.METHOD_NAME, HttpPost.METHOD_NAME, HttpHead.METHOD_NAME};
@Override
protected boolean isRedirectable(final String method) {
return Arrays.stream(REDIRECT_METHODS)
.anyMatch(m -> m.equalsIgnoreCase(method));
}
}).build();
response = client.execute(new HttpPost("http://t.co/I5YYd9tddw"));
assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
}
/**
* Allows you do override the HTTP Client used to execute the requests.
* By default, it used a custom client without cookies.
*
* @return the HTTP Client instance
*/
protected HttpClient newHttpClient() {
return HttpClients.custom()
// Do not manage redirection.
.setRedirectStrategy(new DefaultRedirectStrategy() {
@Override
protected boolean isRedirectable(String method) {
return followRedirect(method);
}
})
.setDefaultCookieStore(new BasicCookieStore() {
@Override
public synchronized List<Cookie> getCookies() {
return Collections.emptyList();
}
})
.build();
}
private TestHttpClient createHttpClient() {
TestHttpClient client = new TestHttpClient();
client.setRedirectStrategy(new DefaultRedirectStrategy() {
@Override
public boolean isRedirected(final HttpRequest request, final HttpResponse response, final HttpContext context) throws ProtocolException {
if (response.getStatusLine().getStatusCode() == StatusCodes.FOUND) {
return true;
}
return super.isRedirected(request, response, context);
}
});
return client;
}
public MetricFetcher() {
int cores = Runtime.getRuntime().availableProcessors() * 2;
long keepAliveTime = 0;
int queueSize = 2048;
RejectedExecutionHandler handler = new DiscardPolicy();
fetchService = new ThreadPoolExecutor(cores, cores,
keepAliveTime, TimeUnit.MILLISECONDS, new ArrayBlockingQueue<>(queueSize),
new NamedThreadFactory("sentinel-dashboard-metrics-fetchService"), handler);
fetchWorker = new ThreadPoolExecutor(cores, cores,
keepAliveTime, TimeUnit.MILLISECONDS, new ArrayBlockingQueue<>(queueSize),
new NamedThreadFactory("sentinel-dashboard-metrics-fetchWorker"), handler);
IOReactorConfig ioConfig = IOReactorConfig.custom()
.setConnectTimeout(3000)
.setSoTimeout(3000)
.setIoThreadCount(Runtime.getRuntime().availableProcessors() * 2)
.build();
httpclient = HttpAsyncClients.custom()
.setRedirectStrategy(new DefaultRedirectStrategy() {
@Override
protected boolean isRedirectable(final String method) {
return false;
}
}).setMaxConnTotal(4000)
.setMaxConnPerRoute(1000)
.setDefaultIOReactorConfig(ioConfig)
.build();
httpclient.start();
start();
}
public SentinelApiClient() {
IOReactorConfig ioConfig = IOReactorConfig.custom().setConnectTimeout(3000).setSoTimeout(10000)
.setIoThreadCount(Runtime.getRuntime().availableProcessors() * 2).build();
httpClient = HttpAsyncClients.custom().setRedirectStrategy(new DefaultRedirectStrategy() {
@Override
protected boolean isRedirectable(final String method) {
return false;
}
}).setMaxConnTotal(4000).setMaxConnPerRoute(1000).setDefaultIOReactorConfig(ioConfig).build();
httpClient.start();
}
public MetricFetcher() {
int cores = Runtime.getRuntime().availableProcessors() * 2;
long keepAliveTime = 0;
int queueSize = 2048;
RejectedExecutionHandler handler = new DiscardPolicy();
fetchService = new ThreadPoolExecutor(cores, cores,
keepAliveTime, TimeUnit.MILLISECONDS, new ArrayBlockingQueue<>(queueSize),
new NamedThreadFactory("sentinel-dashboard-metrics-fetchService"), handler);
fetchWorker = new ThreadPoolExecutor(cores, cores,
keepAliveTime, TimeUnit.MILLISECONDS, new ArrayBlockingQueue<>(queueSize),
new NamedThreadFactory("sentinel-dashboard-metrics-fetchWorker"), handler);
IOReactorConfig ioConfig = IOReactorConfig.custom()
.setConnectTimeout(3000)
.setSoTimeout(3000)
.setIoThreadCount(Runtime.getRuntime().availableProcessors() * 2)
.build();
httpclient = HttpAsyncClients.custom()
.setRedirectStrategy(new DefaultRedirectStrategy() {
@Override
protected boolean isRedirectable(final String method) {
return false;
}
}).setMaxConnTotal(4000)
.setMaxConnPerRoute(1000)
.setDefaultIOReactorConfig(ioConfig)
.build();
httpclient.start();
start();
}
public SentinelApiClient() {
IOReactorConfig ioConfig = IOReactorConfig.custom().setConnectTimeout(3000).setSoTimeout(10000)
.setIoThreadCount(Runtime.getRuntime().availableProcessors() * 2).build();
httpClient = HttpAsyncClients.custom().setRedirectStrategy(new DefaultRedirectStrategy() {
@Override
protected boolean isRedirectable(final String method) {
return false;
}
}).setMaxConnTotal(4000).setMaxConnPerRoute(1000).setDefaultIOReactorConfig(ioConfig).build();
httpClient.start();
}
private static Container createContainer(int uiPort, File testDir) throws Exception {
File adminFile = new File(testDir, "admin.json");
Files.asCharSink(adminFile, UTF_8).write("{\"web\":{\"port\":" + uiPort + "}}");
Container container;
if (Containers.useJavaagent()) {
container = new JavaagentContainer(testDir, true, ImmutableList.of());
} else {
container = new LocalContainer(testDir, true, ImmutableMap.of());
}
// wait for UI to be available (UI starts asynchronously in order to not block startup)
CloseableHttpClient httpClient = HttpClients.custom()
.setRedirectStrategy(new DefaultRedirectStrategy())
.build();
Stopwatch stopwatch = Stopwatch.createStarted();
Exception lastException = null;
while (stopwatch.elapsed(SECONDS) < 10) {
HttpGet request = new HttpGet("http://localhost:" + uiPort);
try (CloseableHttpResponse response = httpClient.execute(request);
InputStream content = response.getEntity().getContent()) {
ByteStreams.exhaust(content);
lastException = null;
break;
} catch (Exception e) {
lastException = e;
}
}
httpClient.close();
if (lastException != null) {
throw new IllegalStateException("Timed out waiting for Glowroot UI", lastException);
}
return container;
}
/**
* Gets HttpClient object
*
* @return HttpClient
*/
private static CloseableHttpClient getHttpClient(int timeout)
{
RequestConfig config = RequestConfig.custom()
.setConnectTimeout(timeout)
.setConnectionRequestTimeout(timeout)
.setSocketTimeout(timeout)
.build();
Registry<ConnectionSocketFactory> registry =
RegistryBuilder.<ConnectionSocketFactory>create()
.register("http",
new HttpUtil.SFConnectionSocketFactory())
.build();
// Build a connection manager with enough connections
PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(registry);
connectionManager.setMaxTotal(1);
connectionManager.setDefaultMaxPerRoute(10);
HttpClientBuilder httpClientBuilder = HttpClientBuilder.create()
.setDefaultRequestConfig(config)
.setConnectionManager(connectionManager)
// Support JVM proxy settings
.useSystemProperties()
.setRedirectStrategy(new DefaultRedirectStrategy())
.disableCookieManagement();
if (HttpUtil.useProxy)
{
// use the custom proxy properties
HttpHost proxy = new HttpHost(HttpUtil.proxyHost, HttpUtil.proxyPort);
SdkProxyRoutePlanner sdkProxyRoutePlanner = new SdkProxyRoutePlanner(
HttpUtil.proxyHost, HttpUtil.proxyPort, HttpUtil.nonProxyHosts
);
httpClientBuilder = httpClientBuilder
.setProxy(proxy)
.setRoutePlanner(sdkProxyRoutePlanner);
if (!Strings.isNullOrEmpty(HttpUtil.proxyUser) && !Strings.isNullOrEmpty(HttpUtil.proxyPassword))
{
Credentials credentials =
new UsernamePasswordCredentials(HttpUtil.proxyUser, HttpUtil.proxyPassword);
AuthScope authScope = new AuthScope(HttpUtil.proxyHost, HttpUtil.proxyPort);
CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
credentialsProvider.setCredentials(authScope, credentials);
httpClientBuilder = httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
}
}
// using the default HTTP client
return httpClientBuilder.build();
}