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 @@ public String generateKey(final HttpHost host, final HttpRequest req) {
uri = URIUtils.rewriteURI(uri, host); uri = URIUtils.rewriteURI(uri, host);
} }
return normalize(uri).toASCIIString(); return normalize(uri).toASCIIString();
} catch (URISyntaxException ex) { } catch (final URISyntaxException ex) {
return req.getRequestUri(); return req.getRequestUri();
} }
} }
@ -103,7 +103,7 @@ public String generateKey(final URL url) {
} }
try { try {
return normalize(url.toURI()).toASCIIString(); return normalize(url.toURI()).toASCIIString();
} catch (URISyntaxException ex) { } catch (final URISyntaxException ex) {
return url.toString(); return url.toString();
} }
} }

View File

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

View File

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

View File

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

View File

@ -61,7 +61,7 @@ public Socket createLayeredSocket(final Socket socket,
} }
// blindly verify the host if in the trust list // 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)) { if (createMatcher(trustedHost).matches(target)) {
return socket; return socket;
} }

View File

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

View File

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

View File

@ -47,29 +47,29 @@
*/ */
public class AsyncClientHttp1Pipelining { 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) .setConnectTimeout(5000)
.setSoTimeout(5000) .setSoTimeout(5000)
.build(); .build();
CloseableHttpAsyncClient client = HttpAsyncClients.custom() final CloseableHttpAsyncClient client = HttpAsyncClients.custom()
.setProtocolVersion(HttpVersion.HTTP_1_1) .setProtocolVersion(HttpVersion.HTTP_1_1)
.setIOReactorConfig(ioReactorConfig) .setIOReactorConfig(ioReactorConfig)
.build(); .build();
client.start(); client.start();
HttpHost target = new HttpHost("httpbin.org"); final HttpHost target = new HttpHost("httpbin.org");
Future<AsyncClientEndpoint> leaseFuture = client.lease(target, null); final Future<AsyncClientEndpoint> leaseFuture = client.lease(target, null);
AsyncClientEndpoint endpoint = leaseFuture.get(30, TimeUnit.SECONDS); final AsyncClientEndpoint endpoint = leaseFuture.get(30, TimeUnit.SECONDS);
try { 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); final CountDownLatch latch = new CountDownLatch(requestUris.length);
for (final String requestUri: requestUris) { 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( endpoint.execute(
new SimpleRequestProducer(request), new SimpleRequestProducer(request),
new SimpleResponseConsumer(), new SimpleResponseConsumer(),

View File

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

View File

@ -54,18 +54,18 @@
*/ */
public class AsyncClientHttp2ServerPush { 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) .setConnectTimeout(5000)
.setSoTimeout(5000) .setSoTimeout(5000)
.build(); .build();
H2Config h2Config = H2Config.custom() final H2Config h2Config = H2Config.custom()
.setPushEnabled(true) .setPushEnabled(true)
.build(); .build();
CloseableHttpAsyncClient client = HttpAsyncClients.custom() final CloseableHttpAsyncClient client = HttpAsyncClients.custom()
.setIOReactorConfig(ioReactorConfig) .setIOReactorConfig(ioReactorConfig)
.setProtocolVersion(HttpVersion.HTTP_2) .setProtocolVersion(HttpVersion.HTTP_2)
.setH2Config(h2Config) .setH2Config(h2Config)
@ -116,7 +116,7 @@ public void releaseResources() {
final HttpHost target = new HttpHost("http2bin.org"); final HttpHost target = new HttpHost("http2bin.org");
final String requestURI = "/"; final String requestURI = "/";
Future<Void> future = client.execute( final Future<Void> future = client.execute(
AsyncRequestBuilder.get(target, requestURI).build(), AsyncRequestBuilder.get(target, requestURI).build(),
new AbstractCharResponseConsumer<Void>() { new AbstractCharResponseConsumer<Void>() {

View File

@ -44,25 +44,25 @@
*/ */
public class AsyncClientHttpExchange { 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) .setConnectTimeout(5000)
.setSoTimeout(5000) .setSoTimeout(5000)
.build(); .build();
CloseableHttpAsyncClient client = HttpAsyncClients.custom() final CloseableHttpAsyncClient client = HttpAsyncClients.custom()
.setIOReactorConfig(ioReactorConfig) .setIOReactorConfig(ioReactorConfig)
.build(); .build();
client.start(); client.start();
HttpHost target = new HttpHost("httpbin.org"); final HttpHost target = new HttpHost("httpbin.org");
String[] requestUris = new String[] {"/", "/ip", "/user-agent", "/headers"}; final String[] requestUris = new String[] {"/", "/ip", "/user-agent", "/headers"};
for (final String requestUri: requestUris) { for (final String requestUri: requestUris) {
SimpleHttpRequest request = new SimpleHttpRequest("GET", target, requestUri, null, null); final SimpleHttpRequest request = new SimpleHttpRequest("GET", target, requestUri, null, null);
Future<SimpleHttpResponse> future = client.execute( final Future<SimpleHttpResponse> future = client.execute(
new SimpleRequestProducer(request), new SimpleRequestProducer(request),
new SimpleResponseConsumer(), new SimpleResponseConsumer(),
new FutureCallback<SimpleHttpResponse>() { new FutureCallback<SimpleHttpResponse>() {

View File

@ -47,24 +47,24 @@
*/ */
public class AsyncClientHttpExchangeStreaming { 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) .setConnectTimeout(5000)
.setSoTimeout(5000) .setSoTimeout(5000)
.build(); .build();
CloseableHttpAsyncClient client = HttpAsyncClients.custom() final CloseableHttpAsyncClient client = HttpAsyncClients.custom()
.setIOReactorConfig(ioReactorConfig) .setIOReactorConfig(ioReactorConfig)
.build(); .build();
client.start(); client.start();
HttpHost target = new HttpHost("httpbin.org"); final HttpHost target = new HttpHost("httpbin.org");
String[] requestUris = new String[] {"/", "/ip", "/user-agent", "/headers"}; final String[] requestUris = new String[] {"/", "/ip", "/user-agent", "/headers"};
for (final String requestUri: requestUris) { for (final String requestUri: requestUris) {
Future<Void> future = client.execute( final Future<Void> future = client.execute(
AsyncRequestBuilder.get(target, requestUri).build(), AsyncRequestBuilder.get(target, requestUri).build(),
new AbstractCharResponseConsumer<Void>() { new AbstractCharResponseConsumer<Void>() {

View File

@ -37,9 +37,9 @@
*/ */
public class ClientAbortMethod { 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()) { 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()); System.out.println("Executing request " + httpget.getMethod() + " " + httpget.getUri());
try (CloseableHttpResponse response = httpclient.execute(httpget)) { try (CloseableHttpResponse response = httpclient.execute(httpget)) {

View File

@ -41,15 +41,15 @@
*/ */
public class ClientAuthentication { public class ClientAuthentication {
public static void main(String[] args) throws Exception { public static void main(final String[] args) throws Exception {
BasicCredentialsProvider credsProvider = new BasicCredentialsProvider(); final BasicCredentialsProvider credsProvider = new BasicCredentialsProvider();
credsProvider.setCredentials( credsProvider.setCredentials(
new AuthScope("httpbin.org", 80), new AuthScope("httpbin.org", 80),
new UsernamePasswordCredentials("user", "passwd".toCharArray())); new UsernamePasswordCredentials("user", "passwd".toCharArray()));
try (CloseableHttpClient httpclient = HttpClients.custom() try (CloseableHttpClient httpclient = HttpClients.custom()
.setDefaultCredentialsProvider(credsProvider) .setDefaultCredentialsProvider(credsProvider)
.build()) { .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()); System.out.println("Executing request " + httpget.getMethod() + " " + httpget.getUri());
try (CloseableHttpResponse response = httpclient.execute(httpget)) { try (CloseableHttpResponse response = httpclient.execute(httpget)) {

View File

@ -42,17 +42,17 @@
*/ */
public class ClientChunkEncodedPost { public class ClientChunkEncodedPost {
public static void main(String[] args) throws Exception { public static void main(final String[] args) throws Exception {
if (args.length != 1) { if (args.length != 1) {
System.out.println("File path not given"); System.out.println("File path not given");
System.exit(1); System.exit(1);
} }
try (CloseableHttpClient httpclient = HttpClients.createDefault()) { 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); new FileInputStream(file), -1, ContentType.APPLICATION_OCTET_STREAM);
reqEntity.setChunked(true); reqEntity.setChunked(true);
// It may be more appropriate to use FileEntity class in this particular // It may be more appropriate to use FileEntity class in this particular

View File

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

View File

@ -42,9 +42,9 @@
*/ */
public class ClientConnectionRelease { 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()) { 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()); System.out.println("Executing request " + httpget.getMethod() + " " + httpget.getUri());
try (CloseableHttpResponse response = httpclient.execute(httpget)) { try (CloseableHttpResponse response = httpclient.execute(httpget)) {
@ -52,7 +52,7 @@ public final static void main(String[] args) throws Exception {
System.out.println(response.getCode() + " " + response.getReasonPhrase()); System.out.println(response.getCode() + " " + response.getReasonPhrase());
// Get hold of the response entity // 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 // If the response does not enclose an entity, there is no need
// to bother about connection release // to bother about connection release
@ -60,7 +60,7 @@ public final static void main(String[] args) throws Exception {
try (InputStream instream = entity.getContent()) { try (InputStream instream = entity.getContent()) {
instream.read(); instream.read();
// do something useful with the response // do something useful with the response
} catch (IOException ex) { } catch (final IOException ex) {
// In case of an IOException the connection will be released // In case of an IOException the connection will be released
// back to the connection manager automatically // back to the connection manager automatically
throw ex; throw ex;

View File

@ -45,24 +45,24 @@
*/ */
public class ClientCustomContext { 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()) { try (CloseableHttpClient httpclient = HttpClients.createDefault()) {
// Create a local instance of cookie store // Create a local instance of cookie store
CookieStore cookieStore = new BasicCookieStore(); final CookieStore cookieStore = new BasicCookieStore();
// Create local HTTP context // Create local HTTP context
HttpClientContext localContext = HttpClientContext.create(); final HttpClientContext localContext = HttpClientContext.create();
// Bind custom cookie store to the local context // Bind custom cookie store to the local context
localContext.setCookieStore(cookieStore); 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()); System.out.println("Executing request " + httpget.getMethod() + " " + httpget.getUri());
// Pass local context as a parameter // Pass local context as a parameter
try (CloseableHttpResponse response = httpclient.execute(httpget, localContext)) { try (CloseableHttpResponse response = httpclient.execute(httpget, localContext)) {
System.out.println("----------------------------------------"); System.out.println("----------------------------------------");
System.out.println(response.getCode() + " " + response.getReasonPhrase()); 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++) { for (int i = 0; i < cookies.size(); i++) {
System.out.println("Local cookie: " + cookies.get(i)); System.out.println("Local cookie: " + cookies.get(i));
} }

View File

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

View File

@ -47,26 +47,26 @@
*/ */
public class ClientCustomSSL { 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 // Trust own CA and all self-signed certs
SSLContext sslcontext = SSLContexts.custom() final SSLContext sslcontext = SSLContexts.custom()
.loadTrustMaterial(new File("my.keystore"), "nopassword".toCharArray(), .loadTrustMaterial(new File("my.keystore"), "nopassword".toCharArray(),
new TrustSelfSignedStrategy()) new TrustSelfSignedStrategy())
.build(); .build();
// Allow TLSv1.2 protocol only // Allow TLSv1.2 protocol only
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory( final SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
sslcontext, sslcontext,
new String[] { "TLSv1.2" }, new String[] { "TLSv1.2" },
null, null,
SSLConnectionSocketFactory.getDefaultHostnameVerifier()); SSLConnectionSocketFactory.getDefaultHostnameVerifier());
HttpClientConnectionManager cm = PoolingHttpClientConnectionManagerBuilder.create() final HttpClientConnectionManager cm = PoolingHttpClientConnectionManagerBuilder.create()
.setSSLSocketFactory(sslsf) .setSSLSocketFactory(sslsf)
.build(); .build();
try (CloseableHttpClient httpclient = HttpClients.custom() try (CloseableHttpClient httpclient = HttpClients.custom()
.setConnectionManager(cm) .setConnectionManager(cm)
.build()) { .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()); System.out.println("Executing request " + httpget.getMethod() + " " + httpget.getUri());

View File

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

View File

@ -42,15 +42,15 @@
*/ */
public class ClientExecuteProxy { 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()) { try (CloseableHttpClient httpclient = HttpClients.createDefault()) {
HttpHost target = new HttpHost("httpbin.org", 443, "https"); final HttpHost target = new HttpHost("httpbin.org", 443, "https");
HttpHost proxy = new HttpHost("127.0.0.1", 8080, "http"); final HttpHost proxy = new HttpHost("127.0.0.1", 8080, "http");
RequestConfig config = RequestConfig.custom() final RequestConfig config = RequestConfig.custom()
.setProxy(proxy) .setProxy(proxy)
.build(); .build();
HttpGet request = new HttpGet("/get"); final HttpGet request = new HttpGet("/get");
request.setConfig(config); request.setConfig(config);
System.out.println("Executing request " + request.getMethod() + " " + request.getUri() + System.out.println("Executing request " + request.getMethod() + " " + request.getUri() +

View File

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

View File

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

View File

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

View File

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

View File

@ -46,20 +46,20 @@
*/ */
public class ClientPreemptiveBasicAuthentication { 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()) { try (CloseableHttpClient httpclient = HttpClients.createDefault()) {
// Generate BASIC scheme object and add it to the local auth cache // 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())); 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 // Add AuthCache to the execution context
HttpClientContext localContext = HttpClientContext.create(); final HttpClientContext localContext = HttpClientContext.create();
localContext.resetAuthExchange(target, basicAuth); 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()); System.out.println("Executing request " + httpget.getMethod() + " " + httpget.getUri());
for (int i = 0; i < 3; i++) { for (int i = 0; i < 3; i++) {

View File

@ -49,24 +49,24 @@
*/ */
public class ClientPreemptiveDigestAuthentication { 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()) { try (CloseableHttpClient httpclient = HttpClients.createDefault()) {
// Create AuthCache instance // 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 // 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 // Suppose we already know the realm name and the expected nonce value
digestAuth.initPreemptive(new UsernamePasswordCredentials("user", "passwd".toCharArray()), "whatever", "realm"); 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); authCache.put(target, digestAuth);
// Add AuthCache to the execution context // Add AuthCache to the execution context
HttpClientContext localContext = HttpClientContext.create(); final HttpClientContext localContext = HttpClientContext.create();
localContext.setAuthCache(authCache); 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()); System.out.println("Executing request " + httpget.getMethod() + " " + httpget.getUri());
for (int i = 0; i < 3; i++) { for (int i = 0; i < 3; i++) {

View File

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

View File

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

View File

@ -46,24 +46,24 @@
*/ */
public class ClientWithResponseHandler { 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()) { 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()); System.out.println("Executing request " + httpget.getMethod() + " " + httpget.getUri());
// Create a custom response handler // Create a custom response handler
ResponseHandler<String> responseHandler = new ResponseHandler<String>() { final ResponseHandler<String> responseHandler = new ResponseHandler<String>() {
@Override @Override
public String handleResponse( public String handleResponse(
final ClassicHttpResponse response) throws IOException { final ClassicHttpResponse response) throws IOException {
int status = response.getCode(); final int status = response.getCode();
if (status >= HttpStatus.SC_SUCCESS && status < HttpStatus.SC_REDIRECTION) { if (status >= HttpStatus.SC_SUCCESS && status < HttpStatus.SC_REDIRECTION) {
HttpEntity entity = response.getEntity(); final HttpEntity entity = response.getEntity();
try { try {
return entity != null ? EntityUtils.toString(entity) : null; return entity != null ? EntityUtils.toString(entity) : null;
} catch (ParseException ex) { } catch (final ParseException ex) {
throw new ClientProtocolException(ex); throw new ClientProtocolException(ex);
} }
} else { } else {
@ -72,7 +72,7 @@ public String handleResponse(
} }
}; };
String responseBody = httpclient.execute(httpget, responseHandler); final String responseBody = httpclient.execute(httpget, responseHandler);
System.out.println("----------------------------------------"); System.out.println("----------------------------------------");
System.out.println(responseBody); System.out.println(responseBody);
} }

View File

@ -43,21 +43,21 @@
*/ */
public class ProxyTunnelDemo { 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(); final ProxyClient proxyClient = new ProxyClient();
HttpHost target = new HttpHost("www.yahoo.com", 80); final HttpHost target = new HttpHost("www.yahoo.com", 80);
HttpHost proxy = new HttpHost("localhost", 8888); final HttpHost proxy = new HttpHost("localhost", 8888);
UsernamePasswordCredentials credentials = new UsernamePasswordCredentials("user", "pwd".toCharArray()); final UsernamePasswordCredentials credentials = new UsernamePasswordCredentials("user", "pwd".toCharArray());
try (Socket socket = proxyClient.tunnel(proxy, target, credentials)) { 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("GET / HTTP/1.1\r\n");
out.write("Host: " + target.toHostString() + "\r\n"); out.write("Host: " + target.toHostString() + "\r\n");
out.write("Agent: whatever\r\n"); out.write("Agent: whatever\r\n");
out.write("Connection: close\r\n"); out.write("Connection: close\r\n");
out.write("\r\n"); out.write("\r\n");
out.flush(); out.flush();
BufferedReader in = new BufferedReader( final BufferedReader in = new BufferedReader(
new InputStreamReader(socket.getInputStream(), StandardCharsets.ISO_8859_1)); new InputStreamReader(socket.getInputStream(), StandardCharsets.ISO_8859_1));
String line = null; String line = null;
while ((line = in.readLine()) != null) { while ((line = in.readLine()) != null) {

View File

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

View File

@ -67,7 +67,7 @@ public void completed(final E result) {
try { try {
contentType = ContentType.parse(entityDetails.getContentType()); contentType = ContentType.parse(entityDetails.getContentType());
resultCallback.completed(buildResult(response, result, contentType)); resultCallback.completed(buildResult(response, result, contentType));
} catch (UnsupportedCharsetException ex) { } catch (final UnsupportedCharsetException ex) {
resultCallback.failed(ex); resultCallback.failed(ex);
} }
} }

View File

@ -50,7 +50,7 @@ public final void consumePromise(
final ContentType contentType; final ContentType contentType;
try { try {
contentType = ContentType.parse(entityDetails.getContentType()); contentType = ContentType.parse(entityDetails.getContentType());
} catch (UnsupportedCharsetException ex) { } catch (final UnsupportedCharsetException ex) {
throw new UnsupportedEncodingException(ex.getMessage()); throw new UnsupportedEncodingException(ex.getMessage());
} }
start(promise, response, contentType); start(promise, response, contentType);

View File

@ -55,7 +55,7 @@ public final void consumeResponse(
try { try {
final ContentType contentType = ContentType.parse(entityDetails.getContentType()); final ContentType contentType = ContentType.parse(entityDetails.getContentType());
start(response, contentType); start(response, contentType);
} catch (UnsupportedCharsetException ex) { } catch (final UnsupportedCharsetException ex) {
throw new UnsupportedEncodingException(ex.getMessage()); throw new UnsupportedEncodingException(ex.getMessage());
} }
} else { } else {

View File

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

View File

@ -57,7 +57,7 @@ public final void consumeResponse(
final ContentType contentType; final ContentType contentType;
try { try {
contentType = ContentType.parse(entityDetails.getContentType()); contentType = ContentType.parse(entityDetails.getContentType());
} catch (UnsupportedCharsetException ex) { } catch (final UnsupportedCharsetException ex) {
throw new UnsupportedEncodingException(ex.getMessage()); throw new UnsupportedEncodingException(ex.getMessage());
} }
Charset charset = contentType != null ? contentType.getCharset() : null; Charset charset = contentType != null ? contentType.getCharset() : null;

View File

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

View File

@ -133,7 +133,7 @@ private void logFrameInfo(final String prefix, final RawFrame frame) {
final LogAppendable logAppendable = new LogAppendable(frameLog, prefix); final LogAppendable logAppendable = new LogAppendable(frameLog, prefix);
framePrinter.printFrameInfo(frame, logAppendable); framePrinter.printFrameInfo(frame, logAppendable);
logAppendable.flush(); logAppendable.flush();
} catch (IOException ignore) { } catch (final IOException ignore) {
} }
} }
@ -142,7 +142,7 @@ private void logFramePayload(final String prefix, final RawFrame frame) {
final LogAppendable logAppendable = new LogAppendable(framePayloadLog, prefix); final LogAppendable logAppendable = new LogAppendable(framePayloadLog, prefix);
framePrinter.printPayload(frame, logAppendable); framePrinter.printPayload(frame, logAppendable);
logAppendable.flush(); logAppendable.flush();
} catch (IOException ignore) { } catch (final IOException ignore) {
} }
} }

View File

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

View File

@ -131,7 +131,7 @@ private static MinimalHttpAsyncClient createMinimalImpl(
new DefaultThreadFactory("httpclient-main", true), new DefaultThreadFactory("httpclient-main", true),
new DefaultThreadFactory("httpclient-dispatch", true), new DefaultThreadFactory("httpclient-dispatch", true),
connmgr); connmgr);
} catch (IOReactorException ex) { } catch (final IOReactorException ex) {
throw new IllegalStateException(ex.getMessage(), ex); throw new IllegalStateException(ex.getMessage(), ex);
} }
} }

View File

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

View File

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

View File

@ -184,7 +184,7 @@ private void readObject(final ObjectInputStream in) throws IOException, ClassNot
in.defaultReadObject(); in.defaultReadObject();
try { try {
this.charset = Charset.forName(in.readUTF()); this.charset = Charset.forName(in.readUTF());
} catch (UnsupportedCharsetException ex) { } catch (final UnsupportedCharsetException ex) {
this.charset = StandardCharsets.US_ASCII; this.charset = StandardCharsets.US_ASCII;
} }
} }

View File

@ -209,7 +209,7 @@ public X509Certificate[] getAcceptedIssuers()
sslContext.init( null, new TrustManager[] sslContext.init( null, new TrustManager[]
{ tm }, null ); { tm }, null );
} }
catch ( KeyManagementException e ) catch ( final KeyManagementException e )
{ {
throw new RuntimeException( "SSL Context initialization error: " + e.getMessage(), e ); throw new RuntimeException( "SSL Context initialization error: " + e.getMessage(), e );
} }
@ -409,11 +409,11 @@ private Certificate getPeerServerCertificate() throws AuthenticationException
{ {
peerCertificates = sslEngine.getSession().getPeerCertificates(); peerCertificates = sslEngine.getSession().getPeerCertificates();
} }
catch ( SSLPeerUnverifiedException e ) catch ( final SSLPeerUnverifiedException e )
{ {
throw new AuthenticationException( e.getMessage(), e ); throw new AuthenticationException( e.getMessage(), e );
} }
for ( Certificate peerCertificate : peerCertificates ) for ( final Certificate peerCertificate : peerCertificates )
{ {
if ( !( peerCertificate instanceof X509Certificate ) ) if ( !( peerCertificate instanceof X509Certificate ) )
{ {
@ -535,7 +535,7 @@ private byte[] createAuthInfo( final NTCredentials ntcredentials ) throws Authen
{ {
return ntlmOutgoingHandle.signAndEncryptMessage( authInfo ); return ntlmOutgoingHandle.signAndEncryptMessage( authInfo );
} }
catch ( NTLMEngineException e ) catch ( final NTLMEngineException e )
{ {
throw new AuthenticationException( e.getMessage(), e ); throw new AuthenticationException( e.getMessage(), e );
} }
@ -607,7 +607,7 @@ private byte[] getSubjectPublicKeyDer( final PublicKey publicKey ) throws Authen
buf.get( subjectPublicKey ); buf.get( subjectPublicKey );
return subjectPublicKey; return subjectPublicKey;
} }
catch ( MalformedChallengeException e ) catch ( final MalformedChallengeException e )
{ {
throw new AuthenticationException( e.getMessage(), e ); throw new AuthenticationException( e.getMessage(), e );
} }
@ -620,7 +620,7 @@ private void beginTlsHandshake() throws AuthenticationException
{ {
getSSLEngine().beginHandshake(); getSSLEngine().beginHandshake();
} }
catch ( SSLException e ) catch ( final SSLException e )
{ {
throw new AuthenticationException( "SSL Engine error: " + e.getMessage(), e ); throw new AuthenticationException( "SSL Engine error: " + e.getMessage(), e );
} }
@ -675,7 +675,7 @@ private void wrap( final ByteBuffer src, final ByteBuffer dst ) throws Authentic
throw new AuthenticationException( "SSL Engine error status: " + engineResult.getStatus() ); 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 ); throw new AuthenticationException( "SSL Engine wrap error: " + e.getMessage(), e );
} }
@ -725,7 +725,7 @@ private void unwrap( final ByteBuffer src, final ByteBuffer dst ) throws Malform
} }
} }
catch ( SSLException e ) catch ( final SSLException e )
{ {
throw new MalformedChallengeException( "SSL Engine unwrap error: " + e.getMessage(), e ); throw new MalformedChallengeException( "SSL Engine unwrap error: " + e.getMessage(), e );
} }

View File

@ -56,7 +56,7 @@ public static void dump( final StringBuilder sb, final byte[] bytes )
sb.append( "null" ); sb.append( "null" );
return; return;
} }
for ( byte b : bytes ) for ( final byte b : bytes )
{ {
sb.append( String.format( "%02X ", b ) ); sb.append( String.format( "%02X ", b ) );
} }

View File

@ -257,7 +257,7 @@ private String createDigestResponse(final HttpRequest request) throws Authentica
Charset charset; Charset charset;
try { try {
charset = charsetName != null ? Charset.forName(charsetName) : StandardCharsets.ISO_8859_1; charset = charsetName != null ? Charset.forName(charsetName) : StandardCharsets.ISO_8859_1;
} catch (UnsupportedCharsetException ex) { } catch (final UnsupportedCharsetException ex) {
charset = StandardCharsets.ISO_8859_1; charset = StandardCharsets.ISO_8859_1;
} }

View File

@ -874,7 +874,7 @@ private Cipher initCipher() throws NTLMEngineException
cipher.init( Cipher.DECRYPT_MODE, new SecretKeySpec( sealingKey, "RC4" ) ); cipher.init( Cipher.DECRYPT_MODE, new SecretKeySpec( sealingKey, "RC4" ) );
} }
} }
catch ( Exception e ) catch ( final Exception e )
{ {
throw new NTLMEngineException( e.getMessage(), e ); throw new NTLMEngineException( e.getMessage(), e );
} }
@ -1854,7 +1854,7 @@ static int rotintlft(final int val, final int numbits) {
static MessageDigest getMD5() { static MessageDigest getMD5() {
try { try {
return MessageDigest.getInstance("MD5"); 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); throw new RuntimeException("MD5 message digest doesn't seem to exist - fatal error: "+ex.getMessage(), ex);
} }
} }

View File

@ -152,7 +152,7 @@ public Credentials getCredentials(final AuthScope authscope, final HttpContext c
systemcreds = new PasswordAuthentication(proxyUser, proxyPassword != null ? proxyPassword.toCharArray() : new char[] {}); systemcreds = new PasswordAuthentication(proxyUser, proxyPassword != null ? proxyPassword.toCharArray() : new char[] {});
} }
} }
} catch (NumberFormatException ex) { } catch (final NumberFormatException ex) {
} }
} }
} }

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -90,7 +90,7 @@ private static HttpHost determineTarget(final ClassicHttpRequest request) throws
URI requestURI = null; URI requestURI = null;
try { try {
requestURI = request.getUri(); requestURI = request.getUri();
} catch (URISyntaxException ignore) { } catch (final URISyntaxException ignore) {
} }
if (requestURI != null && requestURI.isAbsolute()) { if (requestURI != null && requestURI.isAbsolute()) {
target = URIUtils.extractHost(requestURI); target = URIUtils.extractHost(requestURI);

View File

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

View File

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

View File

@ -301,7 +301,7 @@ static List<SubjectName> getSubjectAltNames(final X509Certificate cert) {
return Collections.emptyList(); return Collections.emptyList();
} }
final List<SubjectName> result = new ArrayList<>(); 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; final Integer type = entry.size() >= 2 ? (Integer) entry.get(0) : null;
if (type != null) { if (type != null) {
final String s = (String) entry.get(1); final String s = (String) entry.get(1);

View File

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

View File

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