Use final.

git-svn-id: https://svn.apache.org/repos/asf/httpcomponents/httpclient/trunk@1788709 13f79535-47bb-0310-9956-ffa450edef68
This commit is contained in:
Gary D. Gregory 2017-03-26 02:43:03 +00:00
parent 857bcfb04d
commit b1f8cd58f6
61 changed files with 245 additions and 245 deletions

View File

@ -92,7 +92,7 @@ class CacheKeyGenerator {
uri = URIUtils.rewriteURI(uri, host);
}
return normalize(uri).toASCIIString();
} catch (URISyntaxException ex) {
} catch (final URISyntaxException ex) {
return req.getRequestUri();
}
}
@ -103,7 +103,7 @@ class CacheKeyGenerator {
}
try {
return normalize(url.toURI()).toASCIIString();
} catch (URISyntaxException ex) {
} catch (final URISyntaxException ex) {
return url.toString();
}
}

View File

@ -145,7 +145,7 @@ public class Executor {
final HttpHost httpHost;
try {
httpHost = HttpHost.create(host);
} catch (URISyntaxException ex) {
} catch (final URISyntaxException ex) {
throw new IllegalArgumentException("Invalid host: " + host);
}
return auth(httpHost, creds);
@ -170,7 +170,7 @@ public class Executor {
final HttpHost httpHost;
try {
httpHost = HttpHost.create(host);
} catch (URISyntaxException ex) {
} catch (final URISyntaxException ex) {
throw new IllegalArgumentException("Invalid host: " + host);
}
return authPreemptive(httpHost);
@ -195,7 +195,7 @@ public class Executor {
final HttpHost httpHost;
try {
httpHost = HttpHost.create(proxy);
} catch (URISyntaxException ex) {
} catch (final URISyntaxException ex) {
throw new IllegalArgumentException("Invalid host: " + proxy);
}
return authPreemptiveProxy(httpHost);

View File

@ -305,7 +305,7 @@ public class Request {
public Request viaProxy(final String proxy) {
try {
this.proxy = HttpHost.create(proxy);
} catch (URISyntaxException e) {
} catch (final URISyntaxException e) {
throw new IllegalArgumentException("Invalid host");
}
return this;

View File

@ -90,7 +90,7 @@ public class Response {
assertNotConsumed();
try {
return handler.handleResponse(this.response);
} catch (HttpException ex) {
} catch (final HttpException ex) {
throw new ClientProtocolException(ex);
} finally {
dispose();

View File

@ -61,7 +61,7 @@ final class RelaxedLayeredConnectionSocketFactory implements LayeredConnectionSo
}
// blindly verify the host if in the trust list
for (String trustedHost : trustedHostsConfiguration.getTrustedHosts()) {
for (final String trustedHost : trustedHostsConfiguration.getTrustedHosts()) {
if (createMatcher(trustedHost).matches(target)) {
return socket;
}

View File

@ -53,7 +53,7 @@ public class WeakListTest {
boolean thrown = false;
try {
it.next();
} catch (NoSuchElementException e) {
} catch (final NoSuchElementException e) {
thrown = true;
}
assertTrue(thrown);

View File

@ -45,14 +45,14 @@ import org.apache.hc.core5.reactor.IOReactorConfig;
*/
public class AsyncClientConnectionEviction {
public static void main(String[] args) throws Exception {
public static void main(final String[] args) throws Exception {
IOReactorConfig ioReactorConfig = IOReactorConfig.custom()
final IOReactorConfig ioReactorConfig = IOReactorConfig.custom()
.setConnectTimeout(5000)
.setSoTimeout(5000)
.build();
CloseableHttpAsyncClient client = HttpAsyncClients.custom()
final CloseableHttpAsyncClient client = HttpAsyncClients.custom()
.setIOReactorConfig(ioReactorConfig)
.evictExpiredConnections()
.evictIdleConnections(10, TimeUnit.SECONDS)
@ -60,7 +60,7 @@ public class AsyncClientConnectionEviction {
client.start();
HttpHost target = new HttpHost("httpbin.org");
final HttpHost target = new HttpHost("httpbin.org");
final SimpleHttpRequest request = new SimpleHttpRequest("GET", target, "/", null, null);
final Future<SimpleHttpResponse> future1 = client.execute(

View File

@ -47,29 +47,29 @@ import org.apache.hc.core5.reactor.IOReactorConfig;
*/
public class AsyncClientHttp1Pipelining {
public static void main(String[] args) throws Exception {
public static void main(final String[] args) throws Exception {
IOReactorConfig ioReactorConfig = IOReactorConfig.custom()
final IOReactorConfig ioReactorConfig = IOReactorConfig.custom()
.setConnectTimeout(5000)
.setSoTimeout(5000)
.build();
CloseableHttpAsyncClient client = HttpAsyncClients.custom()
final CloseableHttpAsyncClient client = HttpAsyncClients.custom()
.setProtocolVersion(HttpVersion.HTTP_1_1)
.setIOReactorConfig(ioReactorConfig)
.build();
client.start();
HttpHost target = new HttpHost("httpbin.org");
Future<AsyncClientEndpoint> leaseFuture = client.lease(target, null);
AsyncClientEndpoint endpoint = leaseFuture.get(30, TimeUnit.SECONDS);
final HttpHost target = new HttpHost("httpbin.org");
final Future<AsyncClientEndpoint> leaseFuture = client.lease(target, null);
final AsyncClientEndpoint endpoint = leaseFuture.get(30, TimeUnit.SECONDS);
try {
String[] requestUris = new String[] {"/", "/ip", "/user-agent", "/headers"};
final String[] requestUris = new String[] {"/", "/ip", "/user-agent", "/headers"};
final CountDownLatch latch = new CountDownLatch(requestUris.length);
for (final String requestUri: requestUris) {
SimpleHttpRequest request = new SimpleHttpRequest("GET", target, requestUri, null, null);
final SimpleHttpRequest request = new SimpleHttpRequest("GET", target, requestUri, null, null);
endpoint.execute(
new SimpleRequestProducer(request),
new SimpleResponseConsumer(),

View File

@ -49,18 +49,18 @@ import org.apache.hc.core5.reactor.IOReactorConfig;
*/
public class AsyncClientHttp2Multiplexing {
public static void main(String[] args) throws Exception {
public static void main(final String[] args) throws Exception {
IOReactorConfig ioReactorConfig = IOReactorConfig.custom()
final IOReactorConfig ioReactorConfig = IOReactorConfig.custom()
.setConnectTimeout(5000)
.setSoTimeout(5000)
.build();
H2Config h2Config = H2Config.custom()
final H2Config h2Config = H2Config.custom()
.setPushEnabled(false)
.build();
CloseableHttpAsyncClient client = HttpAsyncClients.custom()
final CloseableHttpAsyncClient client = HttpAsyncClients.custom()
.setIOReactorConfig(ioReactorConfig)
.setProtocolVersion(HttpVersion.HTTP_2)
.setH2Config(h2Config)
@ -68,15 +68,15 @@ public class AsyncClientHttp2Multiplexing {
client.start();
HttpHost target = new HttpHost("http2bin.org");
Future<AsyncClientEndpoint> leaseFuture = client.lease(target, null);
AsyncClientEndpoint endpoint = leaseFuture.get(30, TimeUnit.SECONDS);
final HttpHost target = new HttpHost("http2bin.org");
final Future<AsyncClientEndpoint> leaseFuture = client.lease(target, null);
final AsyncClientEndpoint endpoint = leaseFuture.get(30, TimeUnit.SECONDS);
try {
String[] requestUris = new String[] {"/", "/ip", "/user-agent", "/headers"};
final String[] requestUris = new String[] {"/", "/ip", "/user-agent", "/headers"};
final CountDownLatch latch = new CountDownLatch(requestUris.length);
for (final String requestUri: requestUris) {
SimpleHttpRequest request = new SimpleHttpRequest("GET", target, requestUri, null, null);
final SimpleHttpRequest request = new SimpleHttpRequest("GET", target, requestUri, null, null);
endpoint.execute(
new SimpleRequestProducer(request),
new SimpleResponseConsumer(),

View File

@ -54,18 +54,18 @@ import org.apache.hc.core5.reactor.IOReactorConfig;
*/
public class AsyncClientHttp2ServerPush {
public static void main(String[] args) throws Exception {
public static void main(final String[] args) throws Exception {
IOReactorConfig ioReactorConfig = IOReactorConfig.custom()
final IOReactorConfig ioReactorConfig = IOReactorConfig.custom()
.setConnectTimeout(5000)
.setSoTimeout(5000)
.build();
H2Config h2Config = H2Config.custom()
final H2Config h2Config = H2Config.custom()
.setPushEnabled(true)
.build();
CloseableHttpAsyncClient client = HttpAsyncClients.custom()
final CloseableHttpAsyncClient client = HttpAsyncClients.custom()
.setIOReactorConfig(ioReactorConfig)
.setProtocolVersion(HttpVersion.HTTP_2)
.setH2Config(h2Config)
@ -116,7 +116,7 @@ public class AsyncClientHttp2ServerPush {
final HttpHost target = new HttpHost("http2bin.org");
final String requestURI = "/";
Future<Void> future = client.execute(
final Future<Void> future = client.execute(
AsyncRequestBuilder.get(target, requestURI).build(),
new AbstractCharResponseConsumer<Void>() {

View File

@ -44,25 +44,25 @@ import org.apache.hc.core5.reactor.IOReactorConfig;
*/
public class AsyncClientHttpExchange {
public static void main(String[] args) throws Exception {
public static void main(final String[] args) throws Exception {
IOReactorConfig ioReactorConfig = IOReactorConfig.custom()
final IOReactorConfig ioReactorConfig = IOReactorConfig.custom()
.setConnectTimeout(5000)
.setSoTimeout(5000)
.build();
CloseableHttpAsyncClient client = HttpAsyncClients.custom()
final CloseableHttpAsyncClient client = HttpAsyncClients.custom()
.setIOReactorConfig(ioReactorConfig)
.build();
client.start();
HttpHost target = new HttpHost("httpbin.org");
String[] requestUris = new String[] {"/", "/ip", "/user-agent", "/headers"};
final HttpHost target = new HttpHost("httpbin.org");
final String[] requestUris = new String[] {"/", "/ip", "/user-agent", "/headers"};
for (final String requestUri: requestUris) {
SimpleHttpRequest request = new SimpleHttpRequest("GET", target, requestUri, null, null);
Future<SimpleHttpResponse> future = client.execute(
final SimpleHttpRequest request = new SimpleHttpRequest("GET", target, requestUri, null, null);
final Future<SimpleHttpResponse> future = client.execute(
new SimpleRequestProducer(request),
new SimpleResponseConsumer(),
new FutureCallback<SimpleHttpResponse>() {

View File

@ -47,24 +47,24 @@ import org.apache.hc.core5.reactor.IOReactorConfig;
*/
public class AsyncClientHttpExchangeStreaming {
public static void main(String[] args) throws Exception {
public static void main(final String[] args) throws Exception {
IOReactorConfig ioReactorConfig = IOReactorConfig.custom()
final IOReactorConfig ioReactorConfig = IOReactorConfig.custom()
.setConnectTimeout(5000)
.setSoTimeout(5000)
.build();
CloseableHttpAsyncClient client = HttpAsyncClients.custom()
final CloseableHttpAsyncClient client = HttpAsyncClients.custom()
.setIOReactorConfig(ioReactorConfig)
.build();
client.start();
HttpHost target = new HttpHost("httpbin.org");
String[] requestUris = new String[] {"/", "/ip", "/user-agent", "/headers"};
final HttpHost target = new HttpHost("httpbin.org");
final String[] requestUris = new String[] {"/", "/ip", "/user-agent", "/headers"};
for (final String requestUri: requestUris) {
Future<Void> future = client.execute(
final Future<Void> future = client.execute(
AsyncRequestBuilder.get(target, requestUri).build(),
new AbstractCharResponseConsumer<Void>() {

View File

@ -37,9 +37,9 @@ import org.apache.hc.client5.http.sync.methods.HttpGet;
*/
public class ClientAbortMethod {
public final static void main(String[] args) throws Exception {
public final static void main(final String[] args) throws Exception {
try (CloseableHttpClient httpclient = HttpClients.createDefault()) {
HttpGet httpget = new HttpGet("http://httpbin.org/get");
final HttpGet httpget = new HttpGet("http://httpbin.org/get");
System.out.println("Executing request " + httpget.getMethod() + " " + httpget.getUri());
try (CloseableHttpResponse response = httpclient.execute(httpget)) {

View File

@ -41,15 +41,15 @@ import org.apache.hc.core5.http.io.entity.EntityUtils;
*/
public class ClientAuthentication {
public static void main(String[] args) throws Exception {
BasicCredentialsProvider credsProvider = new BasicCredentialsProvider();
public static void main(final String[] args) throws Exception {
final BasicCredentialsProvider credsProvider = new BasicCredentialsProvider();
credsProvider.setCredentials(
new AuthScope("httpbin.org", 80),
new UsernamePasswordCredentials("user", "passwd".toCharArray()));
try (CloseableHttpClient httpclient = HttpClients.custom()
.setDefaultCredentialsProvider(credsProvider)
.build()) {
HttpGet httpget = new HttpGet("http://httpbin.org/basic-auth/user/passwd");
final HttpGet httpget = new HttpGet("http://httpbin.org/basic-auth/user/passwd");
System.out.println("Executing request " + httpget.getMethod() + " " + httpget.getUri());
try (CloseableHttpResponse response = httpclient.execute(httpget)) {

View File

@ -42,17 +42,17 @@ import org.apache.hc.core5.http.io.entity.InputStreamEntity;
*/
public class ClientChunkEncodedPost {
public static void main(String[] args) throws Exception {
public static void main(final String[] args) throws Exception {
if (args.length != 1) {
System.out.println("File path not given");
System.exit(1);
}
try (CloseableHttpClient httpclient = HttpClients.createDefault()) {
HttpPost httppost = new HttpPost("http://httpbin.org/post");
final HttpPost httppost = new HttpPost("http://httpbin.org/post");
File file = new File(args[0]);
final File file = new File(args[0]);
InputStreamEntity reqEntity = new InputStreamEntity(
final InputStreamEntity reqEntity = new InputStreamEntity(
new FileInputStream(file), -1, ContentType.APPLICATION_OCTET_STREAM);
reqEntity.setChunked(true);
// It may be more appropriate to use FileEntity class in this particular

View File

@ -87,21 +87,21 @@ import org.apache.hc.core5.util.CharArrayBuffer;
*/
public class ClientConfiguration {
public final static void main(String[] args) throws Exception {
public final static void main(final String[] args) throws Exception {
// Use custom message parser / writer to customize the way HTTP
// messages are parsed from and written out to the data stream.
HttpMessageParserFactory<ClassicHttpResponse> responseParserFactory = new DefaultHttpResponseParserFactory() {
final HttpMessageParserFactory<ClassicHttpResponse> responseParserFactory = new DefaultHttpResponseParserFactory() {
@Override
public HttpMessageParser<ClassicHttpResponse> create(H1Config h1Config) {
LineParser lineParser = new BasicLineParser() {
public HttpMessageParser<ClassicHttpResponse> create(final H1Config h1Config) {
final LineParser lineParser = new BasicLineParser() {
@Override
public Header parseHeader(final CharArrayBuffer buffer) {
try {
return super.parseHeader(buffer);
} catch (ParseException ex) {
} catch (final ParseException ex) {
return new BasicHeader(buffer.toString(), null);
}
}
@ -111,15 +111,15 @@ public class ClientConfiguration {
}
};
HttpMessageWriterFactory<ClassicHttpRequest> requestWriterFactory = new DefaultHttpRequestWriterFactory();
final HttpMessageWriterFactory<ClassicHttpRequest> requestWriterFactory = new DefaultHttpRequestWriterFactory();
// Create HTTP/1.1 protocol configuration
H1Config h1Config = H1Config.custom()
final H1Config h1Config = H1Config.custom()
.setMaxHeaderCount(200)
.setMaxLineLength(2000)
.build();
// Create connection configuration
ConnectionConfig connectionConfig = ConnectionConfig.custom()
final ConnectionConfig connectionConfig = ConnectionConfig.custom()
.setMalformedInputAction(CodingErrorAction.IGNORE)
.setUnmappableInputAction(CodingErrorAction.IGNORE)
.setCharset(StandardCharsets.UTF_8)
@ -129,7 +129,7 @@ public class ClientConfiguration {
// initialization of outgoing HTTP connections. Beside standard connection
// configuration parameters HTTP connection factory can define message
// parser / writer routines to be employed by individual connections.
HttpConnectionFactory<ManagedHttpClientConnection> connFactory = new ManagedHttpClientConnectionFactory(
final HttpConnectionFactory<ManagedHttpClientConnection> connFactory = new ManagedHttpClientConnectionFactory(
h1Config, connectionConfig, requestWriterFactory, responseParserFactory);
// Client HTTP connection objects when fully initialized can be bound to
@ -139,17 +139,17 @@ public class ClientConfiguration {
// SSL context for secure connections can be created either based on
// system or application specific properties.
SSLContext sslcontext = SSLContexts.createSystemDefault();
final SSLContext sslcontext = SSLContexts.createSystemDefault();
// Create a registry of custom connection socket factories for supported
// protocol schemes.
Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
final Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
.register("http", PlainConnectionSocketFactory.INSTANCE)
.register("https", new SSLConnectionSocketFactory(sslcontext))
.build();
// Use custom DNS resolver to override the system DNS resolution.
DnsResolver dnsResolver = new SystemDefaultDnsResolver() {
final DnsResolver dnsResolver = new SystemDefaultDnsResolver() {
@Override
public InetAddress[] resolve(final String host) throws UnknownHostException {
@ -163,11 +163,11 @@ public class ClientConfiguration {
};
// Create a connection manager with custom configuration.
PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(
final PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(
socketFactoryRegistry, connFactory, dnsResolver);
// Create socket configuration
SocketConfig socketConfig = SocketConfig.custom()
final SocketConfig socketConfig = SocketConfig.custom()
.setTcpNoDelay(true)
.build();
// Configure the connection manager to use socket configuration either
@ -183,11 +183,11 @@ public class ClientConfiguration {
connManager.setMaxPerRoute(new HttpRoute(new HttpHost("somehost", 80)), 20);
// Use custom cookie store if necessary.
CookieStore cookieStore = new BasicCookieStore();
final CookieStore cookieStore = new BasicCookieStore();
// Use custom credentials provider if necessary.
CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
// Create global request configuration
RequestConfig defaultRequestConfig = RequestConfig.custom()
final RequestConfig defaultRequestConfig = RequestConfig.custom()
.setCookieSpec(CookieSpecs.DEFAULT)
.setExpectContinueEnabled(true)
.setTargetPreferredAuthSchemes(Arrays.asList(AuthSchemes.NTLM, AuthSchemes.DIGEST))
@ -203,10 +203,10 @@ public class ClientConfiguration {
.setProxy(new HttpHost("myproxy", 8080))
.setDefaultRequestConfig(defaultRequestConfig)
.build()) {
HttpGet httpget = new HttpGet("http://httpbin.org/get");
final HttpGet httpget = new HttpGet("http://httpbin.org/get");
// Request configuration can be overridden at the request level.
// They will take precedence over the one set at the client level.
RequestConfig requestConfig = RequestConfig.copy(defaultRequestConfig)
final RequestConfig requestConfig = RequestConfig.copy(defaultRequestConfig)
.setSocketTimeout(5000)
.setConnectTimeout(5000)
.setConnectionRequestTimeout(5000)
@ -215,7 +215,7 @@ public class ClientConfiguration {
httpget.setConfig(requestConfig);
// Execution context can be customized locally.
HttpClientContext context = HttpClientContext.create();
final HttpClientContext context = HttpClientContext.create();
// Contextual attributes set the local context level will take
// precedence over those set at the client level.
context.setCookieStore(cookieStore);

View File

@ -42,9 +42,9 @@ import org.apache.hc.core5.http.HttpEntity;
*/
public class ClientConnectionRelease {
public final static void main(String[] args) throws Exception {
public final static void main(final String[] args) throws Exception {
try (CloseableHttpClient httpclient = HttpClients.createDefault()) {
HttpGet httpget = new HttpGet("http://httpbin.org/get");
final HttpGet httpget = new HttpGet("http://httpbin.org/get");
System.out.println("Executing request " + httpget.getMethod() + " " + httpget.getUri());
try (CloseableHttpResponse response = httpclient.execute(httpget)) {
@ -52,7 +52,7 @@ public class ClientConnectionRelease {
System.out.println(response.getCode() + " " + response.getReasonPhrase());
// Get hold of the response entity
HttpEntity entity = response.getEntity();
final HttpEntity entity = response.getEntity();
// If the response does not enclose an entity, there is no need
// to bother about connection release
@ -60,7 +60,7 @@ public class ClientConnectionRelease {
try (InputStream instream = entity.getContent()) {
instream.read();
// do something useful with the response
} catch (IOException ex) {
} catch (final IOException ex) {
// In case of an IOException the connection will be released
// back to the connection manager automatically
throw ex;

View File

@ -45,24 +45,24 @@ import org.apache.hc.core5.http.io.entity.EntityUtils;
*/
public class ClientCustomContext {
public final static void main(String[] args) throws Exception {
public final static void main(final String[] args) throws Exception {
try (CloseableHttpClient httpclient = HttpClients.createDefault()) {
// Create a local instance of cookie store
CookieStore cookieStore = new BasicCookieStore();
final CookieStore cookieStore = new BasicCookieStore();
// Create local HTTP context
HttpClientContext localContext = HttpClientContext.create();
final HttpClientContext localContext = HttpClientContext.create();
// Bind custom cookie store to the local context
localContext.setCookieStore(cookieStore);
HttpGet httpget = new HttpGet("http://httpbin.org/cookies");
final HttpGet httpget = new HttpGet("http://httpbin.org/cookies");
System.out.println("Executing request " + httpget.getMethod() + " " + httpget.getUri());
// Pass local context as a parameter
try (CloseableHttpResponse response = httpclient.execute(httpget, localContext)) {
System.out.println("----------------------------------------");
System.out.println(response.getCode() + " " + response.getReasonPhrase());
List<Cookie> cookies = cookieStore.getCookies();
final List<Cookie> cookies = cookieStore.getCookies();
for (int i = 0; i < cookies.size(); i++) {
System.out.println("Local cookie: " + cookies.get(i));
}

View File

@ -51,26 +51,26 @@ import org.apache.hc.core5.ssl.SSLContexts;
*/
public class ClientCustomPublicSuffixList {
public final static void main(String[] args) throws Exception {
public final static void main(final String[] args) throws Exception {
// Use PublicSuffixMatcherLoader to load public suffix list from a file,
// resource or from an arbitrary URL
PublicSuffixMatcher publicSuffixMatcher = PublicSuffixMatcherLoader.load(
final PublicSuffixMatcher publicSuffixMatcher = PublicSuffixMatcherLoader.load(
new URL("https://publicsuffix.org/list/effective_tld_names.dat"));
// Please use the publicsuffix.org URL to download the list no more than once per day !!!
// Please consider making a local copy !!!
RFC6265CookieSpecProvider cookieSpecProvider = new RFC6265CookieSpecProvider(publicSuffixMatcher);
Lookup<CookieSpecProvider> cookieSpecRegistry = RegistryBuilder.<CookieSpecProvider>create()
final RFC6265CookieSpecProvider cookieSpecProvider = new RFC6265CookieSpecProvider(publicSuffixMatcher);
final Lookup<CookieSpecProvider> cookieSpecRegistry = RegistryBuilder.<CookieSpecProvider>create()
.register(CookieSpecs.DEFAULT, cookieSpecProvider)
.register(CookieSpecs.STANDARD, cookieSpecProvider)
.register(CookieSpecs.STANDARD_STRICT, cookieSpecProvider)
.build();
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
final SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
SSLContexts.createDefault(),
new DefaultHostnameVerifier(publicSuffixMatcher));
HttpClientConnectionManager cm = PoolingHttpClientConnectionManagerBuilder.create()
final HttpClientConnectionManager cm = PoolingHttpClientConnectionManagerBuilder.create()
.setSSLSocketFactory(sslsf)
.build();
try (CloseableHttpClient httpclient = HttpClients.custom()
@ -78,7 +78,7 @@ public class ClientCustomPublicSuffixList {
.setDefaultCookieSpecRegistry(cookieSpecRegistry)
.build()) {
HttpGet httpget = new HttpGet("https://httpbin.org/get");
final HttpGet httpget = new HttpGet("https://httpbin.org/get");
System.out.println("Executing request " + httpget.getMethod() + " " + httpget.getUri());

View File

@ -47,26 +47,26 @@ import org.apache.hc.core5.ssl.SSLContexts;
*/
public class ClientCustomSSL {
public final static void main(String[] args) throws Exception {
public final static void main(final String[] args) throws Exception {
// Trust own CA and all self-signed certs
SSLContext sslcontext = SSLContexts.custom()
final SSLContext sslcontext = SSLContexts.custom()
.loadTrustMaterial(new File("my.keystore"), "nopassword".toCharArray(),
new TrustSelfSignedStrategy())
.build();
// Allow TLSv1.2 protocol only
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
final SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
sslcontext,
new String[] { "TLSv1.2" },
null,
SSLConnectionSocketFactory.getDefaultHostnameVerifier());
HttpClientConnectionManager cm = PoolingHttpClientConnectionManagerBuilder.create()
final HttpClientConnectionManager cm = PoolingHttpClientConnectionManagerBuilder.create()
.setSSLSocketFactory(sslsf)
.build();
try (CloseableHttpClient httpclient = HttpClients.custom()
.setConnectionManager(cm)
.build()) {
HttpGet httpget = new HttpGet("https://httpbin.org/");
final HttpGet httpget = new HttpGet("https://httpbin.org/");
System.out.println("Executing request " + httpget.getMethod() + " " + httpget.getUri());

View File

@ -42,8 +42,8 @@ import org.apache.hc.core5.pool.PoolStats;
*/
public class ClientEvictExpiredConnections {
public static void main(String[] args) throws Exception {
PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
public static void main(final String[] args) throws Exception {
final PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
cm.setMaxTotal(100);
try (CloseableHttpClient httpclient = HttpClients.custom()
.setConnectionManager(cm)
@ -51,15 +51,15 @@ public class ClientEvictExpiredConnections {
.evictIdleConnections(5L, TimeUnit.SECONDS)
.build()) {
// create an array of URIs to perform GETs on
String[] urisToGet = {
final String[] urisToGet = {
"http://hc.apache.org/",
"http://hc.apache.org/httpcomponents-core-ga/",
"http://hc.apache.org/httpcomponents-client-ga/",
};
for (int i = 0; i < urisToGet.length; i++) {
String requestURI = urisToGet[i];
HttpGet request = new HttpGet(requestURI);
final String requestURI = urisToGet[i];
final HttpGet request = new HttpGet(requestURI);
System.out.println("Executing request " + request.getMethod() + " " + request.getRequestUri());
@ -70,13 +70,13 @@ public class ClientEvictExpiredConnections {
}
}
PoolStats stats1 = cm.getTotalStats();
final PoolStats stats1 = cm.getTotalStats();
System.out.println("Connections kept alive: " + stats1.getAvailable());
// Sleep 10 sec and let the connection evictor do its job
Thread.sleep(10000);
PoolStats stats2 = cm.getTotalStats();
final PoolStats stats2 = cm.getTotalStats();
System.out.println("Connections kept alive: " + stats2.getAvailable());
}

View File

@ -42,15 +42,15 @@ import org.apache.hc.core5.http.io.entity.EntityUtils;
*/
public class ClientExecuteProxy {
public static void main(String[] args)throws Exception {
public static void main(final String[] args)throws Exception {
try (CloseableHttpClient httpclient = HttpClients.createDefault()) {
HttpHost target = new HttpHost("httpbin.org", 443, "https");
HttpHost proxy = new HttpHost("127.0.0.1", 8080, "http");
final HttpHost target = new HttpHost("httpbin.org", 443, "https");
final HttpHost proxy = new HttpHost("127.0.0.1", 8080, "http");
RequestConfig config = RequestConfig.custom()
final RequestConfig config = RequestConfig.custom()
.setProxy(proxy)
.build();
HttpGet request = new HttpGet("/get");
final HttpGet request = new HttpGet("/get");
request.setConfig(config);
System.out.println("Executing request " + request.getMethod() + " " + request.getUri() +

View File

@ -54,20 +54,20 @@ import org.apache.hc.core5.http.protocol.HttpContext;
*/
public class ClientExecuteSOCKS {
public static void main(String[] args)throws Exception {
Registry<ConnectionSocketFactory> reg = RegistryBuilder.<ConnectionSocketFactory>create()
public static void main(final String[] args)throws Exception {
final Registry<ConnectionSocketFactory> reg = RegistryBuilder.<ConnectionSocketFactory>create()
.register("http", new MyConnectionSocketFactory())
.build();
PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(reg);
final PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(reg);
try (CloseableHttpClient httpclient = HttpClients.custom()
.setConnectionManager(cm)
.build()) {
InetSocketAddress socksaddr = new InetSocketAddress("mysockshost", 1234);
HttpClientContext context = HttpClientContext.create();
final InetSocketAddress socksaddr = new InetSocketAddress("mysockshost", 1234);
final HttpClientContext context = HttpClientContext.create();
context.setAttribute("socks.address", socksaddr);
HttpHost target = new HttpHost("httpbin.org", 80, "http");
HttpGet request = new HttpGet("/get");
final HttpHost target = new HttpHost("httpbin.org", 80, "http");
final HttpGet request = new HttpGet("/get");
System.out.println("Executing request " + request.getMethod() + " " + request.getUri() +
" via SOCKS proxy " + socksaddr);
@ -83,8 +83,8 @@ public class ClientExecuteSOCKS {
@Override
public Socket createSocket(final HttpContext context) throws IOException {
InetSocketAddress socksaddr = (InetSocketAddress) context.getAttribute("socks.address");
Proxy proxy = new Proxy(Proxy.Type.SOCKS, socksaddr);
final InetSocketAddress socksaddr = (InetSocketAddress) context.getAttribute("socks.address");
final Proxy proxy = new Proxy(Proxy.Type.SOCKS, socksaddr);
return new Socket(proxy);
}
@ -107,7 +107,7 @@ public class ClientExecuteSOCKS {
}
try {
sock.connect(remoteAddress, connectTimeout);
} catch (SocketTimeoutException ex) {
} catch (final SocketTimeoutException ex) {
throw new ConnectTimeoutException(ex, host, remoteAddress.getAddress());
}
return sock;

View File

@ -46,20 +46,20 @@ import org.apache.hc.core5.http.io.entity.EntityUtils;
*/
public class ClientFormLogin {
public static void main(String[] args) throws Exception {
BasicCookieStore cookieStore = new BasicCookieStore();
public static void main(final String[] args) throws Exception {
final BasicCookieStore cookieStore = new BasicCookieStore();
try (CloseableHttpClient httpclient = HttpClients.custom()
.setDefaultCookieStore(cookieStore)
.build()) {
HttpGet httpget = new HttpGet("https://someportal/");
final HttpGet httpget = new HttpGet("https://someportal/");
try (CloseableHttpResponse response1 = httpclient.execute(httpget)) {
HttpEntity entity = response1.getEntity();
final HttpEntity entity = response1.getEntity();
System.out.println("Login form get: " + response1.getCode() + " " + response1.getReasonPhrase());
EntityUtils.consume(entity);
System.out.println("Initial set of cookies:");
List<Cookie> cookies = cookieStore.getCookies();
final List<Cookie> cookies = cookieStore.getCookies();
if (cookies.isEmpty()) {
System.out.println("None");
} else {
@ -69,19 +69,19 @@ public class ClientFormLogin {
}
}
HttpUriRequest login = RequestBuilder.post()
final HttpUriRequest login = RequestBuilder.post()
.setUri(new URI("https://someportal/"))
.addParameter("IDToken1", "username")
.addParameter("IDToken2", "password")
.build();
try (CloseableHttpResponse response2 = httpclient.execute(login)) {
HttpEntity entity = response2.getEntity();
final HttpEntity entity = response2.getEntity();
System.out.println("Login form get: " + response2.getCode() + " " + response2.getReasonPhrase());
EntityUtils.consume(entity);
System.out.println("Post logon cookies:");
List<Cookie> cookies = cookieStore.getCookies();
final List<Cookie> cookies = cookieStore.getCookies();
if (cookies.isEmpty()) {
System.out.println("None");
} else {

View File

@ -42,27 +42,27 @@ import org.apache.hc.core5.http.protocol.HttpContext;
*/
public class ClientMultiThreadedExecution {
public static void main(String[] args) throws Exception {
public static void main(final String[] args) throws Exception {
// Create an HttpClient with the ThreadSafeClientConnManager.
// This connection manager must be used if more than one thread will
// be using the HttpClient.
PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
final PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
cm.setMaxTotal(100);
try (CloseableHttpClient httpclient = HttpClients.custom()
.setConnectionManager(cm)
.build()) {
// create an array of URIs to perform GETs on
String[] urisToGet = {
final String[] urisToGet = {
"http://hc.apache.org/",
"http://hc.apache.org/httpcomponents-core-ga/",
"http://hc.apache.org/httpcomponents-client-ga/",
};
// create a thread for each URI
GetThread[] threads = new GetThread[urisToGet.length];
final GetThread[] threads = new GetThread[urisToGet.length];
for (int i = 0; i < threads.length; i++) {
HttpGet httpget = new HttpGet(urisToGet[i]);
final HttpGet httpget = new HttpGet(urisToGet[i]);
threads[i] = new GetThread(httpclient, httpget, i + 1);
}
@ -89,7 +89,7 @@ public class ClientMultiThreadedExecution {
private final HttpGet httpget;
private final int id;
public GetThread(CloseableHttpClient httpClient, HttpGet httpget, int id) {
public GetThread(final CloseableHttpClient httpClient, final HttpGet httpget, final int id) {
this.httpClient = httpClient;
this.context = new BasicHttpContext();
this.httpget = httpget;
@ -106,13 +106,13 @@ public class ClientMultiThreadedExecution {
try (CloseableHttpResponse response = httpClient.execute(httpget, context)) {
System.out.println(id + " - get executed");
// get the response body as an array of bytes
HttpEntity entity = response.getEntity();
final HttpEntity entity = response.getEntity();
if (entity != null) {
byte[] bytes = EntityUtils.toByteArray(entity);
final byte[] bytes = EntityUtils.toByteArray(entity);
System.out.println(id + " - " + bytes.length + " bytes read");
}
}
} catch (Exception e) {
} catch (final Exception e) {
System.out.println(id + " - error: " + e);
}
}

View File

@ -44,19 +44,19 @@ import org.apache.hc.core5.http.io.entity.EntityUtils;
*/
public class ClientMultipartFormPost {
public static void main(String[] args) throws Exception {
public static void main(final String[] args) throws Exception {
if (args.length != 1) {
System.out.println("File path not given");
System.exit(1);
}
try (CloseableHttpClient httpclient = HttpClients.createDefault()) {
HttpPost httppost = new HttpPost("http://localhost:8080" +
final HttpPost httppost = new HttpPost("http://localhost:8080" +
"/servlets-examples/servlet/RequestInfoExample");
FileBody bin = new FileBody(new File(args[0]));
StringBody comment = new StringBody("A binary file of some kind", ContentType.TEXT_PLAIN);
final FileBody bin = new FileBody(new File(args[0]));
final StringBody comment = new StringBody("A binary file of some kind", ContentType.TEXT_PLAIN);
HttpEntity reqEntity = MultipartEntityBuilder.create()
final HttpEntity reqEntity = MultipartEntityBuilder.create()
.addPart("bin", bin)
.addPart("comment", comment)
.build();
@ -68,7 +68,7 @@ public class ClientMultipartFormPost {
try (CloseableHttpResponse response = httpclient.execute(httppost)) {
System.out.println("----------------------------------------");
System.out.println(response);
HttpEntity resEntity = response.getEntity();
final HttpEntity resEntity = response.getEntity();
if (resEntity != null) {
System.out.println("Response content length: " + resEntity.getContentLength());
}

View File

@ -46,20 +46,20 @@ import org.apache.hc.core5.http.io.entity.EntityUtils;
*/
public class ClientPreemptiveBasicAuthentication {
public static void main(String[] args) throws Exception {
public static void main(final String[] args) throws Exception {
try (CloseableHttpClient httpclient = HttpClients.createDefault()) {
// Generate BASIC scheme object and add it to the local auth cache
BasicScheme basicAuth = new BasicScheme();
final BasicScheme basicAuth = new BasicScheme();
basicAuth.initPreemptive(new UsernamePasswordCredentials("user", "passwd".toCharArray()));
HttpHost target = new HttpHost("httpbin.org", 80, "http");
final HttpHost target = new HttpHost("httpbin.org", 80, "http");
// Add AuthCache to the execution context
HttpClientContext localContext = HttpClientContext.create();
final HttpClientContext localContext = HttpClientContext.create();
localContext.resetAuthExchange(target, basicAuth);
HttpGet httpget = new HttpGet("http://httpbin.org/hidden-basic-auth/user/passwd");
final HttpGet httpget = new HttpGet("http://httpbin.org/hidden-basic-auth/user/passwd");
System.out.println("Executing request " + httpget.getMethod() + " " + httpget.getUri());
for (int i = 0; i < 3; i++) {

View File

@ -49,24 +49,24 @@ import org.apache.hc.core5.http.io.entity.EntityUtils;
*/
public class ClientPreemptiveDigestAuthentication {
public static void main(String[] args) throws Exception {
public static void main(final String[] args) throws Exception {
try (CloseableHttpClient httpclient = HttpClients.createDefault()) {
// Create AuthCache instance
AuthCache authCache = new BasicAuthCache();
final AuthCache authCache = new BasicAuthCache();
// Generate DIGEST scheme object, initialize it and add it to the local auth cache
DigestScheme digestAuth = new DigestScheme();
final DigestScheme digestAuth = new DigestScheme();
// Suppose we already know the realm name and the expected nonce value
digestAuth.initPreemptive(new UsernamePasswordCredentials("user", "passwd".toCharArray()), "whatever", "realm");
HttpHost target = new HttpHost("httpbin.org", 80, "http");
final HttpHost target = new HttpHost("httpbin.org", 80, "http");
authCache.put(target, digestAuth);
// Add AuthCache to the execution context
HttpClientContext localContext = HttpClientContext.create();
final HttpClientContext localContext = HttpClientContext.create();
localContext.setAuthCache(authCache);
HttpGet httpget = new HttpGet("http://httpbin.org/digest-auth/auth/user/passwd");
final HttpGet httpget = new HttpGet("http://httpbin.org/digest-auth/auth/user/passwd");
System.out.println("Executing request " + httpget.getMethod() + " " + httpget.getUri());
for (int i = 0; i < 3; i++) {

View File

@ -43,8 +43,8 @@ import org.apache.hc.core5.http.io.entity.EntityUtils;
*/
public class ClientProxyAuthentication {
public static void main(String[] args) throws Exception {
BasicCredentialsProvider credsProvider = new BasicCredentialsProvider();
public static void main(final String[] args) throws Exception {
final BasicCredentialsProvider credsProvider = new BasicCredentialsProvider();
credsProvider.setCredentials(
new AuthScope("localhost", 8888),
new UsernamePasswordCredentials("squid", "squid".toCharArray()));
@ -53,13 +53,13 @@ public class ClientProxyAuthentication {
new UsernamePasswordCredentials("user", "passwd".toCharArray()));
try (CloseableHttpClient httpclient = HttpClients.custom()
.setDefaultCredentialsProvider(credsProvider).build()) {
HttpHost target = new HttpHost("httpbin.org", 80, "http");
HttpHost proxy = new HttpHost("localhost", 8888);
final HttpHost target = new HttpHost("httpbin.org", 80, "http");
final HttpHost proxy = new HttpHost("localhost", 8888);
RequestConfig config = RequestConfig.custom()
final RequestConfig config = RequestConfig.custom()
.setProxy(proxy)
.build();
HttpGet httpget = new HttpGet("/basic-auth/user/passwd");
final HttpGet httpget = new HttpGet("/basic-auth/user/passwd");
httpget.setConfig(config);
System.out.println("Executing request " + httpget.getMethod() + " " + httpget.getUri() +

View File

@ -47,61 +47,61 @@ import org.apache.hc.core5.http.io.ResponseHandler;
public class ClientWithRequestFuture {
public static void main(String[] args) throws Exception {
public static void main(final String[] args) throws Exception {
// the simplest way to create a HttpAsyncClientWithFuture
HttpClientConnectionManager cm = PoolingHttpClientConnectionManagerBuilder.create()
final HttpClientConnectionManager cm = PoolingHttpClientConnectionManagerBuilder.create()
.setMaxConnPerRoute(5)
.setMaxConnTotal(5)
.build();
CloseableHttpClient httpclient = HttpClientBuilder.create()
final CloseableHttpClient httpclient = HttpClientBuilder.create()
.setConnectionManager(cm)
.build();
ExecutorService execService = Executors.newFixedThreadPool(5);
final ExecutorService execService = Executors.newFixedThreadPool(5);
try (FutureRequestExecutionService requestExecService = new FutureRequestExecutionService(
httpclient, execService)) {
// Because things are asynchronous, you must provide a ResponseHandler
ResponseHandler<Boolean> handler = new ResponseHandler<Boolean>() {
final ResponseHandler<Boolean> handler = new ResponseHandler<Boolean>() {
@Override
public Boolean handleResponse(ClassicHttpResponse response) throws IOException {
public Boolean handleResponse(final ClassicHttpResponse response) throws IOException {
// simply return true if the status was OK
return response.getCode() == HttpStatus.SC_OK;
}
};
// Simple request ...
HttpGet request1 = new HttpGet("http://httpbin.org/get");
HttpRequestFutureTask<Boolean> futureTask1 = requestExecService.execute(request1,
final HttpGet request1 = new HttpGet("http://httpbin.org/get");
final HttpRequestFutureTask<Boolean> futureTask1 = requestExecService.execute(request1,
HttpClientContext.create(), handler);
Boolean wasItOk1 = futureTask1.get();
final Boolean wasItOk1 = futureTask1.get();
System.out.println("It was ok? " + wasItOk1);
// Cancel a request
try {
HttpGet request2 = new HttpGet("http://httpbin.org/get");
HttpRequestFutureTask<Boolean> futureTask2 = requestExecService.execute(request2,
final HttpGet request2 = new HttpGet("http://httpbin.org/get");
final HttpRequestFutureTask<Boolean> futureTask2 = requestExecService.execute(request2,
HttpClientContext.create(), handler);
futureTask2.cancel(true);
Boolean wasItOk2 = futureTask2.get();
final Boolean wasItOk2 = futureTask2.get();
System.out.println("It was cancelled so it should never print this: " + wasItOk2);
} catch (CancellationException e) {
} catch (final CancellationException e) {
System.out.println("We cancelled it, so this is expected");
}
// Request with a timeout
HttpGet request3 = new HttpGet("http://httpbin.org/get");
HttpRequestFutureTask<Boolean> futureTask3 = requestExecService.execute(request3,
final HttpGet request3 = new HttpGet("http://httpbin.org/get");
final HttpRequestFutureTask<Boolean> futureTask3 = requestExecService.execute(request3,
HttpClientContext.create(), handler);
Boolean wasItOk3 = futureTask3.get(10, TimeUnit.SECONDS);
final Boolean wasItOk3 = futureTask3.get(10, TimeUnit.SECONDS);
System.out.println("It was ok? " + wasItOk3);
FutureCallback<Boolean> callback = new FutureCallback<Boolean>() {
final FutureCallback<Boolean> callback = new FutureCallback<Boolean>() {
@Override
public void completed(Boolean result) {
public void completed(final Boolean result) {
System.out.println("completed with " + result);
}
@Override
public void failed(Exception ex) {
public void failed(final Exception ex) {
System.out.println("failed with " + ex.getMessage());
}
@ -112,12 +112,12 @@ public class ClientWithRequestFuture {
};
// Simple request with a callback
HttpGet request4 = new HttpGet("http://httpbin.org/get");
final HttpGet request4 = new HttpGet("http://httpbin.org/get");
// using a null HttpContext here since it is optional
// the callback will be called when the task completes, fails, or is cancelled
HttpRequestFutureTask<Boolean> futureTask4 = requestExecService.execute(request4,
final HttpRequestFutureTask<Boolean> futureTask4 = requestExecService.execute(request4,
HttpClientContext.create(), handler, callback);
Boolean wasItOk4 = futureTask4.get(10, TimeUnit.SECONDS);
final Boolean wasItOk4 = futureTask4.get(10, TimeUnit.SECONDS);
System.out.println("It was ok? " + wasItOk4);
}
}

View File

@ -46,24 +46,24 @@ import org.apache.hc.core5.http.io.entity.EntityUtils;
*/
public class ClientWithResponseHandler {
public final static void main(String[] args) throws Exception {
public final static void main(final String[] args) throws Exception {
try (CloseableHttpClient httpclient = HttpClients.createDefault()) {
HttpGet httpget = new HttpGet("http://httpbin.org/get");
final HttpGet httpget = new HttpGet("http://httpbin.org/get");
System.out.println("Executing request " + httpget.getMethod() + " " + httpget.getUri());
// Create a custom response handler
ResponseHandler<String> responseHandler = new ResponseHandler<String>() {
final ResponseHandler<String> responseHandler = new ResponseHandler<String>() {
@Override
public String handleResponse(
final ClassicHttpResponse response) throws IOException {
int status = response.getCode();
final int status = response.getCode();
if (status >= HttpStatus.SC_SUCCESS && status < HttpStatus.SC_REDIRECTION) {
HttpEntity entity = response.getEntity();
final HttpEntity entity = response.getEntity();
try {
return entity != null ? EntityUtils.toString(entity) : null;
} catch (ParseException ex) {
} catch (final ParseException ex) {
throw new ClientProtocolException(ex);
}
} else {
@ -72,7 +72,7 @@ public class ClientWithResponseHandler {
}
};
String responseBody = httpclient.execute(httpget, responseHandler);
final String responseBody = httpclient.execute(httpget, responseHandler);
System.out.println("----------------------------------------");
System.out.println(responseBody);
}

View File

@ -43,21 +43,21 @@ import org.apache.hc.core5.http.HttpHost;
*/
public class ProxyTunnelDemo {
public final static void main(String[] args) throws Exception {
public final static void main(final String[] args) throws Exception {
ProxyClient proxyClient = new ProxyClient();
HttpHost target = new HttpHost("www.yahoo.com", 80);
HttpHost proxy = new HttpHost("localhost", 8888);
UsernamePasswordCredentials credentials = new UsernamePasswordCredentials("user", "pwd".toCharArray());
final ProxyClient proxyClient = new ProxyClient();
final HttpHost target = new HttpHost("www.yahoo.com", 80);
final HttpHost proxy = new HttpHost("localhost", 8888);
final UsernamePasswordCredentials credentials = new UsernamePasswordCredentials("user", "pwd".toCharArray());
try (Socket socket = proxyClient.tunnel(proxy, target, credentials)) {
Writer out = new OutputStreamWriter(socket.getOutputStream(), StandardCharsets.ISO_8859_1);
final Writer out = new OutputStreamWriter(socket.getOutputStream(), StandardCharsets.ISO_8859_1);
out.write("GET / HTTP/1.1\r\n");
out.write("Host: " + target.toHostString() + "\r\n");
out.write("Agent: whatever\r\n");
out.write("Connection: close\r\n");
out.write("\r\n");
out.flush();
BufferedReader in = new BufferedReader(
final BufferedReader in = new BufferedReader(
new InputStreamReader(socket.getInputStream(), StandardCharsets.ISO_8859_1));
String line = null;
while ((line = in.readLine()) != null) {

View File

@ -42,9 +42,9 @@ import org.apache.hc.core5.http.message.BasicNameValuePair;
public class QuickStart {
public static void main(String[] args) throws Exception {
public static void main(final String[] args) throws Exception {
try (CloseableHttpClient httpclient = HttpClients.createDefault()) {
HttpGet httpGet = new HttpGet("http://httpbin.org/get");
final HttpGet httpGet = new HttpGet("http://httpbin.org/get");
// The underlying HTTP connection is still held by the response object
// to allow the response content to be streamed directly from the network socket.
// In order to ensure correct deallocation of system resources
@ -54,21 +54,21 @@ public class QuickStart {
// by the connection manager.
try (CloseableHttpResponse response1 = httpclient.execute(httpGet)) {
System.out.println(response1.getCode() + " " + response1.getReasonPhrase());
HttpEntity entity1 = response1.getEntity();
final HttpEntity entity1 = response1.getEntity();
// do something useful with the response body
// and ensure it is fully consumed
EntityUtils.consume(entity1);
}
HttpPost httpPost = new HttpPost("http://httpbin.org/post");
List<NameValuePair> nvps = new ArrayList<>();
final HttpPost httpPost = new HttpPost("http://httpbin.org/post");
final List<NameValuePair> nvps = new ArrayList<>();
nvps.add(new BasicNameValuePair("username", "vip"));
nvps.add(new BasicNameValuePair("password", "secret"));
httpPost.setEntity(new UrlEncodedFormEntity(nvps));
try (CloseableHttpResponse response2 = httpclient.execute(httpPost)) {
System.out.println(response2.getCode() + " " + response2.getReasonPhrase());
HttpEntity entity2 = response2.getEntity();
final HttpEntity entity2 = response2.getEntity();
// do something useful with the response body
// and ensure it is fully consumed
EntityUtils.consume(entity2);

View File

@ -67,7 +67,7 @@ public abstract class AbstractAsyncResponseConsumer<T, E> implements AsyncRespon
try {
contentType = ContentType.parse(entityDetails.getContentType());
resultCallback.completed(buildResult(response, result, contentType));
} catch (UnsupportedCharsetException ex) {
} catch (final UnsupportedCharsetException ex) {
resultCallback.failed(ex);
}
}

View File

@ -50,7 +50,7 @@ public abstract class AbstractBinPushConsumer extends AbstractBinDataConsumer im
final ContentType contentType;
try {
contentType = ContentType.parse(entityDetails.getContentType());
} catch (UnsupportedCharsetException ex) {
} catch (final UnsupportedCharsetException ex) {
throw new UnsupportedEncodingException(ex.getMessage());
}
start(promise, response, contentType);

View File

@ -55,7 +55,7 @@ public abstract class AbstractBinResponseConsumer<T> extends AbstractBinDataCons
try {
final ContentType contentType = ContentType.parse(entityDetails.getContentType());
start(response, contentType);
} catch (UnsupportedCharsetException ex) {
} catch (final UnsupportedCharsetException ex) {
throw new UnsupportedEncodingException(ex.getMessage());
}
} else {

View File

@ -52,7 +52,7 @@ public abstract class AbstractCharPushConsumer extends AbstractCharDataConsumer
final ContentType contentType;
try {
contentType = ContentType.parse(entityDetails.getContentType());
} catch (UnsupportedCharsetException ex) {
} catch (final UnsupportedCharsetException ex) {
throw new UnsupportedEncodingException(ex.getMessage());
}
Charset charset = contentType != null ? contentType.getCharset() : null;

View File

@ -57,7 +57,7 @@ public abstract class AbstractCharResponseConsumer<T> extends AbstractCharDataCo
final ContentType contentType;
try {
contentType = ContentType.parse(entityDetails.getContentType());
} catch (UnsupportedCharsetException ex) {
} catch (final UnsupportedCharsetException ex) {
throw new UnsupportedEncodingException(ex.getMessage());
}
Charset charset = contentType != null ? contentType.getCharset() : null;

View File

@ -101,7 +101,7 @@ abstract class AbstractHttpAsyncClientBase extends CloseableHttpAsyncClient {
public void run() {
try {
ioReactor.execute();
} catch (Exception ex) {
} catch (final Exception ex) {
exceptionListener.onError(ex);
}
}

View File

@ -133,7 +133,7 @@ public class DefaultAsyncHttp2ClientEventHandlerFactory implements IOEventHandle
final LogAppendable logAppendable = new LogAppendable(frameLog, prefix);
framePrinter.printFrameInfo(frame, logAppendable);
logAppendable.flush();
} catch (IOException ignore) {
} catch (final IOException ignore) {
}
}
@ -142,7 +142,7 @@ public class DefaultAsyncHttp2ClientEventHandlerFactory implements IOEventHandle
final LogAppendable logAppendable = new LogAppendable(framePayloadLog, prefix);
framePrinter.printPayload(frame, logAppendable);
logAppendable.flush();
} catch (IOException ignore) {
} catch (final IOException ignore) {
}
}

View File

@ -576,7 +576,7 @@ public class HttpAsyncClientBuilder {
userTokenHandlerCopy,
defaultRequestConfig,
closeablesCopy);
} catch (IOReactorException ex) {
} catch (final IOReactorException ex) {
throw new IllegalStateException(ex.getMessage(), ex);
}
}

View File

@ -131,7 +131,7 @@ public class HttpAsyncClients {
new DefaultThreadFactory("httpclient-main", true),
new DefaultThreadFactory("httpclient-dispatch", true),
connmgr);
} catch (IOReactorException ex) {
} catch (final IOReactorException ex) {
throw new IllegalStateException(ex.getMessage(), ex);
}
}

View File

@ -201,7 +201,7 @@ class InternalHttpAsyncClient extends AbstractHttpAsyncClientBase {
}
});
} catch (HttpException ex) {
} catch (final HttpException ex) {
future.failed(ex);
}
return future;
@ -265,7 +265,7 @@ class InternalHttpAsyncClient extends AbstractHttpAsyncClientBase {
}
});
} catch (HttpException ex) {
} catch (final HttpException ex) {
future.failed(ex);
}
return future;
@ -419,7 +419,7 @@ class InternalHttpAsyncClient extends AbstractHttpAsyncClientBase {
private void closeEndpoint() {
try {
connectionEndpoint.close();
} catch (IOException ex) {
} catch (final IOException ex) {
log.debug("I/O error closing connection endpoint: " + ex.getMessage(), ex);
}
}

View File

@ -265,7 +265,7 @@ class MinimalHttpAsyncClient extends AbstractHttpAsyncClientBase {
if (released.compareAndSet(false, true)) {
try {
connectionEndpoint.close();
} catch (IOException ignore) {
} catch (final IOException ignore) {
}
connmgr.release(connectionEndpoint, null, -1L, TimeUnit.MILLISECONDS);
}

View File

@ -184,7 +184,7 @@ public class BasicScheme implements AuthScheme, Serializable {
in.defaultReadObject();
try {
this.charset = Charset.forName(in.readUTF());
} catch (UnsupportedCharsetException ex) {
} catch (final UnsupportedCharsetException ex) {
this.charset = StandardCharsets.US_ASCII;
}
}

View File

@ -209,7 +209,7 @@ public class CredSspScheme implements AuthScheme
sslContext.init( null, new TrustManager[]
{ tm }, null );
}
catch ( KeyManagementException e )
catch ( final KeyManagementException e )
{
throw new RuntimeException( "SSL Context initialization error: " + e.getMessage(), e );
}
@ -409,11 +409,11 @@ public class CredSspScheme implements AuthScheme
{
peerCertificates = sslEngine.getSession().getPeerCertificates();
}
catch ( SSLPeerUnverifiedException e )
catch ( final SSLPeerUnverifiedException e )
{
throw new AuthenticationException( e.getMessage(), e );
}
for ( Certificate peerCertificate : peerCertificates )
for ( final Certificate peerCertificate : peerCertificates )
{
if ( !( peerCertificate instanceof X509Certificate ) )
{
@ -535,7 +535,7 @@ public class CredSspScheme implements AuthScheme
{
return ntlmOutgoingHandle.signAndEncryptMessage( authInfo );
}
catch ( NTLMEngineException e )
catch ( final NTLMEngineException e )
{
throw new AuthenticationException( e.getMessage(), e );
}
@ -607,7 +607,7 @@ public class CredSspScheme implements AuthScheme
buf.get( subjectPublicKey );
return subjectPublicKey;
}
catch ( MalformedChallengeException e )
catch ( final MalformedChallengeException e )
{
throw new AuthenticationException( e.getMessage(), e );
}
@ -620,7 +620,7 @@ public class CredSspScheme implements AuthScheme
{
getSSLEngine().beginHandshake();
}
catch ( SSLException e )
catch ( final SSLException e )
{
throw new AuthenticationException( "SSL Engine error: " + e.getMessage(), e );
}
@ -675,7 +675,7 @@ public class CredSspScheme implements AuthScheme
throw new AuthenticationException( "SSL Engine error status: " + engineResult.getStatus() );
}
}
catch ( SSLException e )
catch ( final SSLException e )
{
throw new AuthenticationException( "SSL Engine wrap error: " + e.getMessage(), e );
}
@ -725,7 +725,7 @@ public class CredSspScheme implements AuthScheme
}
}
catch ( SSLException e )
catch ( final SSLException e )
{
throw new MalformedChallengeException( "SSL Engine unwrap error: " + e.getMessage(), e );
}

View File

@ -56,7 +56,7 @@ class DebugUtil
sb.append( "null" );
return;
}
for ( byte b : bytes )
for ( final byte b : bytes )
{
sb.append( String.format( "%02X ", b ) );
}

View File

@ -257,7 +257,7 @@ public class DigestScheme implements AuthScheme, Serializable {
Charset charset;
try {
charset = charsetName != null ? Charset.forName(charsetName) : StandardCharsets.ISO_8859_1;
} catch (UnsupportedCharsetException ex) {
} catch (final UnsupportedCharsetException ex) {
charset = StandardCharsets.ISO_8859_1;
}

View File

@ -874,7 +874,7 @@ final class NTLMEngineImpl implements NTLMEngine {
cipher.init( Cipher.DECRYPT_MODE, new SecretKeySpec( sealingKey, "RC4" ) );
}
}
catch ( Exception e )
catch ( final Exception e )
{
throw new NTLMEngineException( e.getMessage(), e );
}
@ -1854,7 +1854,7 @@ final class NTLMEngineImpl implements NTLMEngine {
static MessageDigest getMD5() {
try {
return MessageDigest.getInstance("MD5");
} catch (NoSuchAlgorithmException ex) {
} catch (final NoSuchAlgorithmException ex) {
throw new RuntimeException("MD5 message digest doesn't seem to exist - fatal error: "+ex.getMessage(), ex);
}
}

View File

@ -152,7 +152,7 @@ public class SystemDefaultCredentialsProvider implements CredentialsStore {
systemcreds = new PasswordAuthentication(proxyUser, proxyPassword != null ? proxyPassword.toCharArray() : new char[] {});
}
}
} catch (NumberFormatException ex) {
} catch (final NumberFormatException ex) {
}
}
}

View File

@ -189,7 +189,7 @@ public class BasicHttpClientConnectionManager implements HttpClientConnectionMan
final TimeUnit tunit) throws InterruptedException, ExecutionException, TimeoutException {
try {
return new InternalConnectionEndpoint(route, getConnection(route, state));
} catch (IOException ex) {
} catch (final IOException ex) {
throw new ExecutionException(ex.getMessage(), ex);
}
}

View File

@ -268,7 +268,7 @@ public class PoolingHttpClientConnectionManager
boolean stale;
try {
stale = conn.isStale();
} catch (IOException ignore) {
} catch (final IOException ignore) {
stale = true;
}
if (stale) {
@ -292,7 +292,7 @@ public class PoolingHttpClientConnectionManager
this.endpoint = new InternalConnectionEndpoint(poolEntry);
}
return this.endpoint;
} catch (Exception ex) {
} catch (final Exception ex) {
pool.release(poolEntry, false);
throw new ExecutionException(ex.getMessage(), ex);
}
@ -333,7 +333,7 @@ public class PoolingHttpClientConnectionManager
this.log.debug("Connection " + ConnPoolSupport.getId(conn) + " can be kept alive " + s);
}
}
} catch (RuntimeException ex) {
} catch (final RuntimeException ex) {
reusable = false;
throw ex;
} finally {

View File

@ -82,14 +82,14 @@ final class AsyncClientConnectionOperator {
final InetAddress[] remoteAddresses;
try {
remoteAddresses = dnsResolver.resolve(host.getHostName());
} catch (UnknownHostException ex) {
} catch (final UnknownHostException ex) {
future.failed(ex);
return future;
}
final int port;
try {
port = schemePortResolver.resolve(host);
} catch (UnsupportedSchemeException ex) {
} catch (final UnsupportedSchemeException ex) {
future.failed(ex);
return future;
}

View File

@ -229,7 +229,7 @@ public class PoolingAsyncClientConnectionManager implements AsyncClientConnectio
log.debug("Connection " + ConnPoolSupport.getId(connection) + " can be kept alive " + s);
}
}
} catch (RuntimeException ex) {
} catch (final RuntimeException ex) {
reusable = false;
throw ex;
} finally {

View File

@ -80,7 +80,7 @@ public class DefaultRedirectStrategy<T extends HttpRequest> implements RedirectS
public DefaultRedirectStrategy(final String... safeMethods) {
super();
this.safeMethods = new ConcurrentHashMap<>();
for (String safeMethod: safeMethods) {
for (final String safeMethod: safeMethods) {
this.safeMethods.put(safeMethod.toUpperCase(Locale.ROOT), Boolean.TRUE);
}
}

View File

@ -90,7 +90,7 @@ public abstract class CloseableHttpClient implements HttpClient, Closeable {
URI requestURI = null;
try {
requestURI = request.getUri();
} catch (URISyntaxException ignore) {
} catch (final URISyntaxException ignore) {
}
if (requestURI != null && requestURI.isAbsolute()) {
target = URIUtils.extractHost(requestURI);

View File

@ -876,7 +876,7 @@ public class HttpClientBuilder {
connectionEvictor.shutdown();
try {
connectionEvictor.awaitTermination(1L, TimeUnit.SECONDS);
} catch (InterruptedException interrupted) {
} catch (final InterruptedException interrupted) {
Thread.currentThread().interrupt();
}
}

View File

@ -120,7 +120,7 @@ public class RedirectExec implements ClientExecChain {
final URI redirectUri;
try {
redirectUri = redirect.getUri();
} catch (URISyntaxException ex) {
} catch (final URISyntaxException ex) {
// Should not happen
throw new ProtocolException(ex.getMessage(), ex);
}

View File

@ -301,7 +301,7 @@ public final class DefaultHostnameVerifier implements HttpClientHostnameVerifier
return Collections.emptyList();
}
final List<SubjectName> result = new ArrayList<>();
for (List<?> entry: entries) {
for (final List<?> entry: entries) {
final Integer type = entry.size() >= 2 ? (Integer) entry.get(0) : null;
if (type != null) {
final String s = (String) entry.get(1);

View File

@ -332,7 +332,7 @@ public final class H2TlsSupport {
return null;
}
List<String> enabledProtocols = null;
for (String protocol: protocols) {
for (final String protocol: protocols) {
if (!protocol.startsWith("SSL") && !BLACKLISED_PROTOCOLS.contains(protocol)) {
if (enabledProtocols == null) {
enabledProtocols = new ArrayList<>();
@ -348,7 +348,7 @@ public final class H2TlsSupport {
return null;
}
List<String> enabledCiphers = null;
for (String cipher: ciphers) {
for (final String cipher: ciphers) {
if (!BLACKLISED_CIPHERS.contains(cipher)) {
if (enabledCiphers == null) {
enabledCiphers = new ArrayList<>();

View File

@ -289,7 +289,7 @@ public class RequestBuilder {
try {
uri = request.getUri();
} catch (URISyntaxException ignore) {
} catch (final URISyntaxException ignore) {
}
if (request instanceof Configurable) {
config = ((Configurable) request).getConfig();