HttpClient resource management API made compatible with Java 7 'try with resources': HttpClientBuilder to return CloseableHttpClient and CloseableHttpClient to return CloseableHttpResponse objects which implement java.io.Closeable; made ClientChainExec interface and related classes package private

git-svn-id: https://svn.apache.org/repos/asf/httpcomponents/httpclient/trunk@1405509 13f79535-47bb-0310-9956-ffa450edef68
This commit is contained in:
Oleg Kalnichevski 2012-11-04 07:40:00 +00:00
parent 3c26d6ff41
commit 0155befe4a
64 changed files with 823 additions and 782 deletions

View File

@ -54,7 +54,7 @@ import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.auth.BasicScheme; import org.apache.http.impl.auth.BasicScheme;
import org.apache.http.impl.client.BasicAuthCache; import org.apache.http.impl.client.BasicAuthCache;
import org.apache.http.impl.client.BasicCredentialsProvider; import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.impl.client.builder.HttpClientBuilder;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.protocol.BasicHttpContext; import org.apache.http.protocol.BasicHttpContext;
@ -93,7 +93,7 @@ public class Executor {
CONNMGR = new PoolingHttpClientConnectionManager(schemeRegistry); CONNMGR = new PoolingHttpClientConnectionManager(schemeRegistry);
CONNMGR.setDefaultMaxPerRoute(100); CONNMGR.setDefaultMaxPerRoute(100);
CONNMGR.setMaxTotal(200); CONNMGR.setMaxTotal(200);
CLIENT = new HttpClientBuilder().setConnectionManager(CONNMGR).build(); CLIENT = HttpClientBuilder.create().setConnectionManager(CONNMGR).build();
} }
public static Executor newInstance() { public static Executor newInstance() {

View File

@ -28,10 +28,10 @@
package org.apache.http.examples.client; package org.apache.http.examples.client;
import org.apache.http.HttpEntity; import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse; import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.client.CloseableHttpClient;
/** /**
* This example demonstrates how to abort an HTTP method before its normal completion. * This example demonstrates how to abort an HTTP method before its normal completion.
@ -39,29 +39,30 @@ import org.apache.http.impl.client.DefaultHttpClient;
public class ClientAbortMethod { public class ClientAbortMethod {
public final static void main(String[] args) throws Exception { public final static void main(String[] args) throws Exception {
HttpClient httpclient = new DefaultHttpClient(); CloseableHttpClient httpclient = HttpClients.createDefault();
try { try {
HttpGet httpget = new HttpGet("http://www.apache.org/"); HttpGet httpget = new HttpGet("http://www.apache.org/");
System.out.println("executing request " + httpget.getURI()); System.out.println("executing request " + httpget.getURI());
HttpResponse response = httpclient.execute(httpget); CloseableHttpResponse response = httpclient.execute(httpget);
HttpEntity entity = response.getEntity(); try {
HttpEntity entity = response.getEntity();
System.out.println("----------------------------------------"); System.out.println("----------------------------------------");
System.out.println(response.getStatusLine()); System.out.println(response.getStatusLine());
if (entity != null) { if (entity != null) {
System.out.println("Response content length: " + entity.getContentLength()); System.out.println("Response content length: " + entity.getContentLength());
}
System.out.println("----------------------------------------");
// Do not feel like reading the response body
// Call abort on the request object
httpget.abort();
} finally {
response.close();
} }
System.out.println("----------------------------------------");
// Do not feel like reading the response body
// Call abort on the request object
httpget.abort();
} finally { } finally {
// When HttpClient instance is no longer needed, httpclient.close();
// shut down the connection manager to ensure
// immediate deallocation of all system resources
httpclient.getConnectionManager().shutdown();
} }
} }

View File

@ -26,11 +26,14 @@
package org.apache.http.examples.client; package org.apache.http.examples.client;
import org.apache.http.HttpEntity; import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.auth.AuthScope; import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials; import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils; import org.apache.http.util.EntityUtils;
/** /**
@ -40,29 +43,31 @@ import org.apache.http.util.EntityUtils;
public class ClientAuthentication { public class ClientAuthentication {
public static void main(String[] args) throws Exception { public static void main(String[] args) throws Exception {
DefaultHttpClient httpclient = new DefaultHttpClient(); CredentialsProvider credsProvider = new BasicCredentialsProvider();
credsProvider.setCredentials(
new AuthScope("localhost", 443),
new UsernamePasswordCredentials("username", "password"));
CloseableHttpClient httpclient = HttpClients.custom()
.setCredentialsProvider(credsProvider).build();
try { try {
httpclient.getCredentialsProvider().setCredentials(
new AuthScope("localhost", 443),
new UsernamePasswordCredentials("username", "password"));
HttpGet httpget = new HttpGet("https://localhost/protected"); HttpGet httpget = new HttpGet("https://localhost/protected");
System.out.println("executing request" + httpget.getRequestLine()); System.out.println("executing request" + httpget.getRequestLine());
HttpResponse response = httpclient.execute(httpget); CloseableHttpResponse response = httpclient.execute(httpget);
HttpEntity entity = response.getEntity(); try {
HttpEntity entity = response.getEntity();
System.out.println("----------------------------------------"); System.out.println("----------------------------------------");
System.out.println(response.getStatusLine()); System.out.println(response.getStatusLine());
if (entity != null) { if (entity != null) {
System.out.println("Response content length: " + entity.getContentLength()); System.out.println("Response content length: " + entity.getContentLength());
}
EntityUtils.consume(entity);
} finally {
response.close();
} }
EntityUtils.consume(entity);
} finally { } finally {
// When HttpClient instance is no longer needed, httpclient.close();
// shut down the connection manager to ensure
// immediate deallocation of all system resources
httpclient.getConnectionManager().shutdown();
} }
} }
} }

View File

@ -30,11 +30,11 @@ import java.io.File;
import java.io.FileInputStream; import java.io.FileInputStream;
import org.apache.http.HttpEntity; import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse; import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost; import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.InputStreamEntity; import org.apache.http.entity.InputStreamEntity;
import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils; import org.apache.http.util.EntityUtils;
/** /**
@ -47,7 +47,7 @@ public class ClientChunkEncodedPost {
System.out.println("File path not given"); System.out.println("File path not given");
System.exit(1); System.exit(1);
} }
HttpClient httpclient = new DefaultHttpClient(); CloseableHttpClient httpclient = HttpClients.createDefault();
try { try {
HttpPost httppost = new HttpPost("http://localhost:8080" + HttpPost httppost = new HttpPost("http://localhost:8080" +
"/servlets-examples/servlet/RequestInfoExample"); "/servlets-examples/servlet/RequestInfoExample");
@ -67,21 +67,22 @@ public class ClientChunkEncodedPost {
httppost.setEntity(reqEntity); httppost.setEntity(reqEntity);
System.out.println("executing request " + httppost.getRequestLine()); System.out.println("executing request " + httppost.getRequestLine());
HttpResponse response = httpclient.execute(httppost); CloseableHttpResponse response = httpclient.execute(httppost);
HttpEntity resEntity = response.getEntity(); try {
HttpEntity resEntity = response.getEntity();
System.out.println("----------------------------------------"); System.out.println("----------------------------------------");
System.out.println(response.getStatusLine()); System.out.println(response.getStatusLine());
if (resEntity != null) { if (resEntity != null) {
System.out.println("Response content length: " + resEntity.getContentLength()); System.out.println("Response content length: " + resEntity.getContentLength());
System.out.println("Chunked?: " + resEntity.isChunked()); System.out.println("Chunked?: " + resEntity.isChunked());
}
EntityUtils.consume(resEntity);
} finally {
response.close();
} }
EntityUtils.consume(resEntity);
} finally { } finally {
// When HttpClient instance is no longer needed, httpclient.close();
// shut down the connection manager to ensure
// immediate deallocation of all system resources
httpclient.getConnectionManager().shutdown();
} }
} }

View File

@ -31,10 +31,10 @@ import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import org.apache.http.HttpEntity; import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse; import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
/** /**
* This example demonstrates the recommended way of using API to make sure * This example demonstrates the recommended way of using API to make sure
@ -43,49 +43,42 @@ import org.apache.http.impl.client.DefaultHttpClient;
public class ClientConnectionRelease { public class ClientConnectionRelease {
public final static void main(String[] args) throws Exception { public final static void main(String[] args) throws Exception {
HttpClient httpclient = new DefaultHttpClient(); CloseableHttpClient httpclient = HttpClients.createDefault();
try { try {
HttpGet httpget = new HttpGet("http://www.apache.org/"); HttpGet httpget = new HttpGet("http://www.apache.org/");
// Execute HTTP request // Execute HTTP request
System.out.println("executing request " + httpget.getURI()); System.out.println("executing request " + httpget.getURI());
HttpResponse response = httpclient.execute(httpget); CloseableHttpResponse response = httpclient.execute(httpget);
try {
System.out.println("----------------------------------------");
System.out.println(response.getStatusLine());
System.out.println("----------------------------------------");
System.out.println("----------------------------------------"); // Get hold of the response entity
System.out.println(response.getStatusLine()); HttpEntity entity = response.getEntity();
System.out.println("----------------------------------------");
// Get hold of the response entity // If the response does not enclose an entity, there is no need
HttpEntity entity = response.getEntity(); // to bother about connection release
if (entity != null) {
// If the response does not enclose an entity, there is no need InputStream instream = entity.getContent();
// to bother about connection release try {
if (entity != null) { instream.read();
InputStream instream = entity.getContent(); // do something useful with the response
try { } catch (IOException ex) {
instream.read(); // In case of an IOException the connection will be released
// do something useful with the response // back to the connection manager automatically
} catch (IOException ex) { throw ex;
// In case of an IOException the connection will be released } finally {
// back to the connection manager automatically // Closing the input stream will trigger connection release
throw ex; instream.close();
} catch (RuntimeException ex) { }
// In case of an unexpected exception you may want to abort
// the HTTP request in order to shut down the underlying
// connection immediately.
httpget.abort();
throw ex;
} finally {
// Closing the input stream will trigger connection release
try { instream.close(); } catch (Exception ignore) {}
} }
} finally {
response.close();
} }
} finally { } finally {
// When HttpClient instance is no longer needed, httpclient.close();
// shut down the connection manager to ensure
// immediate deallocation of all system resources
httpclient.getConnectionManager().shutdown();
} }
} }

View File

@ -30,19 +30,18 @@ package org.apache.http.examples.client;
import java.util.List; import java.util.List;
import org.apache.http.HttpEntity; import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.CookieStore; import org.apache.http.client.CookieStore;
import org.apache.http.client.HttpClient; import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.protocol.ClientContext; import org.apache.http.client.protocol.ClientContext;
import org.apache.http.cookie.Cookie; import org.apache.http.cookie.Cookie;
import org.apache.http.impl.client.BasicCookieStore; import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.protocol.HttpContext; import org.apache.http.impl.client.HttpClients;
import org.apache.http.protocol.BasicHttpContext; import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;
import org.apache.http.util.EntityUtils; import org.apache.http.util.EntityUtils;
/** /**
* This example demonstrates the use of a local HTTP context populated with * This example demonstrates the use of a local HTTP context populated with
* custom attributes. * custom attributes.
@ -50,8 +49,7 @@ import org.apache.http.util.EntityUtils;
public class ClientCustomContext { public class ClientCustomContext {
public final static void main(String[] args) throws Exception { public final static void main(String[] args) throws Exception {
CloseableHttpClient httpclient = HttpClients.createDefault();
HttpClient httpclient = new DefaultHttpClient();
try { try {
// Create a local instance of cookie store // Create a local instance of cookie store
CookieStore cookieStore = new BasicCookieStore(); CookieStore cookieStore = new BasicCookieStore();
@ -66,29 +64,29 @@ public class ClientCustomContext {
System.out.println("executing request " + httpget.getURI()); System.out.println("executing request " + httpget.getURI());
// Pass local context as a parameter // Pass local context as a parameter
HttpResponse response = httpclient.execute(httpget, localContext); CloseableHttpResponse response = httpclient.execute(httpget, localContext);
HttpEntity entity = response.getEntity(); try {
HttpEntity entity = response.getEntity();
System.out.println("----------------------------------------"); System.out.println("----------------------------------------");
System.out.println(response.getStatusLine()); System.out.println(response.getStatusLine());
if (entity != null) { if (entity != null) {
System.out.println("Response content length: " + entity.getContentLength()); System.out.println("Response content length: " + entity.getContentLength());
}
List<Cookie> cookies = cookieStore.getCookies();
for (int i = 0; i < cookies.size(); i++) {
System.out.println("Local cookie: " + cookies.get(i));
}
// Consume response content
EntityUtils.consume(entity);
System.out.println("----------------------------------------");
} finally {
response.close();
} }
List<Cookie> cookies = cookieStore.getCookies();
for (int i = 0; i < cookies.size(); i++) {
System.out.println("Local cookie: " + cookies.get(i));
}
// Consume response content
EntityUtils.consume(entity);
System.out.println("----------------------------------------");
} finally { } finally {
// When HttpClient instance is no longer needed, httpclient.close();
// shut down the connection manager to ensure
// immediate deallocation of all system resources
httpclient.getConnectionManager().shutdown();
} }
} }

View File

@ -31,11 +31,11 @@ import java.io.FileInputStream;
import java.security.KeyStore; import java.security.KeyStore;
import org.apache.http.HttpEntity; import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse; import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.ssl.SSLSocketFactory; import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils; import org.apache.http.util.EntityUtils;
/** /**
@ -45,39 +45,36 @@ import org.apache.http.util.EntityUtils;
public class ClientCustomSSL { public class ClientCustomSSL {
public final static void main(String[] args) throws Exception { public final static void main(String[] args) throws Exception {
DefaultHttpClient httpclient = new DefaultHttpClient(); KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
FileInputStream instream = new FileInputStream(new File("my.keystore"));
try {
trustStore.load(instream, "nopassword".toCharArray());
} finally {
instream.close();
}
CloseableHttpClient httpclient = HttpClients.custom()
.setSSLSocketFactory(new SSLSocketFactory(trustStore)).build();
try { try {
KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
FileInputStream instream = new FileInputStream(new File("my.keystore"));
try {
trustStore.load(instream, "nopassword".toCharArray());
} finally {
try { instream.close(); } catch (Exception ignore) {}
}
SSLSocketFactory socketFactory = new SSLSocketFactory(trustStore);
Scheme sch = new Scheme("https", 443, socketFactory);
httpclient.getConnectionManager().getSchemeRegistry().register(sch);
HttpGet httpget = new HttpGet("https://localhost/"); HttpGet httpget = new HttpGet("https://localhost/");
System.out.println("executing request" + httpget.getRequestLine()); System.out.println("executing request" + httpget.getRequestLine());
HttpResponse response = httpclient.execute(httpget); CloseableHttpResponse response = httpclient.execute(httpget);
HttpEntity entity = response.getEntity(); try {
HttpEntity entity = response.getEntity();
System.out.println("----------------------------------------"); System.out.println("----------------------------------------");
System.out.println(response.getStatusLine()); System.out.println(response.getStatusLine());
if (entity != null) { if (entity != null) {
System.out.println("Response content length: " + entity.getContentLength()); System.out.println("Response content length: " + entity.getContentLength());
}
EntityUtils.consume(entity);
} finally {
response.close();
} }
EntityUtils.consume(entity);
} finally { } finally {
// When HttpClient instance is no longer needed, httpclient.close();
// shut down the connection manager to ensure
// immediate deallocation of all system resources
httpclient.getConnectionManager().shutdown();
} }
} }

View File

@ -29,12 +29,12 @@ package org.apache.http.examples.client;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
import org.apache.http.HttpEntity; import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse; import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.ClientConnectionManager; import org.apache.http.conn.HttpClientConnectionManager;
import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.conn.PoolingClientConnectionManager; import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.util.EntityUtils; import org.apache.http.util.EntityUtils;
/** /**
@ -44,10 +44,10 @@ import org.apache.http.util.EntityUtils;
public class ClientEvictExpiredConnections { public class ClientEvictExpiredConnections {
public static void main(String[] args) throws Exception { public static void main(String[] args) throws Exception {
PoolingClientConnectionManager cm = new PoolingClientConnectionManager(); PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
cm.setMaxTotal(100); cm.setMaxTotal(100);
CloseableHttpClient httpclient = HttpClients.custom()
HttpClient httpclient = new DefaultHttpClient(cm); .setConnectionManager(cm).build();
try { try {
// create an array of URIs to perform GETs on // create an array of URIs to perform GETs on
String[] urisToGet = { String[] urisToGet = {
@ -62,21 +62,25 @@ public class ClientEvictExpiredConnections {
for (int i = 0; i < urisToGet.length; i++) { for (int i = 0; i < urisToGet.length; i++) {
String requestURI = urisToGet[i]; String requestURI = urisToGet[i];
HttpGet req = new HttpGet(requestURI); HttpGet request = new HttpGet(requestURI);
System.out.println("executing request " + requestURI); System.out.println("executing request " + requestURI);
HttpResponse rsp = httpclient.execute(req); CloseableHttpResponse response = httpclient.execute(request);
HttpEntity entity = rsp.getEntity(); try {
HttpEntity entity = response.getEntity();
System.out.println("----------------------------------------"); System.out.println("----------------------------------------");
System.out.println(rsp.getStatusLine()); System.out.println(response.getStatusLine());
if (entity != null) { if (entity != null) {
System.out.println("Response content length: " + entity.getContentLength()); System.out.println("Response content length: " + entity.getContentLength());
}
System.out.println("----------------------------------------");
EntityUtils.consume(entity);
} finally {
response.close();
} }
System.out.println("----------------------------------------");
EntityUtils.consume(entity);
} }
// Sleep 10 sec and let the connection evictor do its job // Sleep 10 sec and let the connection evictor do its job
@ -87,20 +91,17 @@ public class ClientEvictExpiredConnections {
connEvictor.join(); connEvictor.join();
} finally { } finally {
// When HttpClient instance is no longer needed, httpclient.close();
// shut down the connection manager to ensure
// immediate deallocation of all system resources
httpclient.getConnectionManager().shutdown();
} }
} }
public static class IdleConnectionEvictor extends Thread { public static class IdleConnectionEvictor extends Thread {
private final ClientConnectionManager connMgr; private final HttpClientConnectionManager connMgr;
private volatile boolean shutdown; private volatile boolean shutdown;
public IdleConnectionEvictor(ClientConnectionManager connMgr) { public IdleConnectionEvictor(HttpClientConnectionManager connMgr) {
super(); super();
this.connMgr = connMgr; this.connMgr = connMgr;
} }

View File

@ -30,10 +30,11 @@ package org.apache.http.examples.client;
import org.apache.http.Header; import org.apache.http.Header;
import org.apache.http.HttpEntity; import org.apache.http.HttpEntity;
import org.apache.http.HttpHost; import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient; import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils; import org.apache.http.util.EntityUtils;
/** /**
@ -44,33 +45,33 @@ import org.apache.http.util.EntityUtils;
public class ClientExecuteDirect { public class ClientExecuteDirect {
public static void main(String[] args) throws Exception { public static void main(String[] args) throws Exception {
DefaultHttpClient httpclient = new DefaultHttpClient(); CloseableHttpClient httpclient = HttpClients.createDefault();
try { try {
HttpHost target = new HttpHost("www.apache.org", 80, "http"); HttpHost target = new HttpHost("www.apache.org", 80, "http");
HttpGet req = new HttpGet("/"); HttpGet request = new HttpGet("/");
System.out.println("executing request to " + target); System.out.println("executing request to " + target);
HttpResponse rsp = httpclient.execute(target, req); CloseableHttpResponse response = httpclient.execute(target, request);
HttpEntity entity = rsp.getEntity(); try {
HttpEntity entity = response.getEntity();
System.out.println("----------------------------------------"); System.out.println("----------------------------------------");
System.out.println(rsp.getStatusLine()); System.out.println(response.getStatusLine());
Header[] headers = rsp.getAllHeaders(); Header[] headers = response.getAllHeaders();
for (int i = 0; i < headers.length; i++) { for (int i = 0; i < headers.length; i++) {
System.out.println(headers[i]); System.out.println(headers[i]);
}
System.out.println("----------------------------------------");
if (entity != null) {
System.out.println(EntityUtils.toString(entity));
}
} finally {
response.close();
} }
System.out.println("----------------------------------------");
if (entity != null) {
System.out.println(EntityUtils.toString(entity));
}
} finally { } finally {
// When HttpClient instance is no longer needed, httpclient.close();
// shut down the connection manager to ensure
// immediate deallocation of all system resources
httpclient.getConnectionManager().shutdown();
} }
} }

View File

@ -30,11 +30,12 @@ package org.apache.http.examples.client;
import org.apache.http.Header; import org.apache.http.Header;
import org.apache.http.HttpEntity; import org.apache.http.HttpEntity;
import org.apache.http.HttpHost; import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient; import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.params.ConnRoutePNames; import org.apache.http.conn.params.ConnRoutePNames;
import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils; import org.apache.http.util.EntityUtils;
/** /**
@ -46,35 +47,34 @@ public class ClientExecuteProxy {
public static void main(String[] args)throws Exception { public static void main(String[] args)throws Exception {
HttpHost proxy = new HttpHost("127.0.0.1", 8080, "http"); HttpHost proxy = new HttpHost("127.0.0.1", 8080, "http");
CloseableHttpClient httpclient = HttpClients.createDefault();
DefaultHttpClient httpclient = new DefaultHttpClient();
try { try {
httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy); httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
HttpHost target = new HttpHost("issues.apache.org", 443, "https"); HttpHost target = new HttpHost("issues.apache.org", 443, "https");
HttpGet req = new HttpGet("/"); HttpGet request = new HttpGet("/");
System.out.println("executing request to " + target + " via " + proxy); System.out.println("executing request to " + target + " via " + proxy);
HttpResponse rsp = httpclient.execute(target, req); CloseableHttpResponse response = httpclient.execute(target, request);
HttpEntity entity = rsp.getEntity(); try {
HttpEntity entity = response.getEntity();
System.out.println("----------------------------------------"); System.out.println("----------------------------------------");
System.out.println(rsp.getStatusLine()); System.out.println(response.getStatusLine());
Header[] headers = rsp.getAllHeaders(); Header[] headers = response.getAllHeaders();
for (int i = 0; i<headers.length; i++) { for (int i = 0; i<headers.length; i++) {
System.out.println(headers[i]); System.out.println(headers[i]);
}
System.out.println("----------------------------------------");
if (entity != null) {
System.out.println(EntityUtils.toString(entity));
}
} finally {
response.close();
} }
System.out.println("----------------------------------------");
if (entity != null) {
System.out.println(EntityUtils.toString(entity));
}
} finally { } finally {
// When HttpClient instance is no longer needed, httpclient.close();
// shut down the connection manager to ensure
// immediate deallocation of all system resources
httpclient.getConnectionManager().shutdown();
} }
} }

View File

@ -37,13 +37,17 @@ import java.net.UnknownHostException;
import org.apache.http.Header; import org.apache.http.Header;
import org.apache.http.HttpEntity; import org.apache.http.HttpEntity;
import org.apache.http.HttpHost; import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient; import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.ConnectTimeoutException; import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.conn.scheme.Scheme; import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.scheme.SchemeSocketFactory; import org.apache.http.conn.scheme.SchemeSocketFactory;
import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.impl.conn.SchemeRegistryFactory;
import org.apache.http.params.HttpConnectionParams; import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams; import org.apache.http.params.HttpParams;
import org.apache.http.util.EntityUtils; import org.apache.http.util.EntityUtils;
@ -56,37 +60,38 @@ import org.apache.http.util.EntityUtils;
public class ClientExecuteSOCKS { public class ClientExecuteSOCKS {
public static void main(String[] args)throws Exception { public static void main(String[] args)throws Exception {
DefaultHttpClient httpclient = new DefaultHttpClient(); SchemeRegistry schemeRegistry = SchemeRegistryFactory.createDefault();
schemeRegistry.register(new Scheme("http", 80, new MySchemeSocketFactory()));
PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
CloseableHttpClient httpclient = HttpClients.custom().setConnectionManager(cm).build();
try { try {
httpclient.getParams().setParameter("socks.host", "mysockshost"); httpclient.getParams().setParameter("socks.host", "mysockshost");
httpclient.getParams().setParameter("socks.port", 1234); httpclient.getParams().setParameter("socks.port", 1234);
httpclient.getConnectionManager().getSchemeRegistry().register(
new Scheme("http", 80, new MySchemeSocketFactory()));
HttpHost target = new HttpHost("www.apache.org", 80, "http"); HttpHost target = new HttpHost("www.apache.org", 80, "http");
HttpGet req = new HttpGet("/"); HttpGet request = new HttpGet("/");
System.out.println("executing request to " + target + " via SOCKS proxy"); System.out.println("executing request to " + target + " via SOCKS proxy");
HttpResponse rsp = httpclient.execute(target, req); CloseableHttpResponse response = httpclient.execute(target, request);
HttpEntity entity = rsp.getEntity(); try {
HttpEntity entity = response.getEntity();
System.out.println("----------------------------------------"); System.out.println("----------------------------------------");
System.out.println(rsp.getStatusLine()); System.out.println(response.getStatusLine());
Header[] headers = rsp.getAllHeaders(); Header[] headers = response.getAllHeaders();
for (int i = 0; i<headers.length; i++) { for (int i = 0; i<headers.length; i++) {
System.out.println(headers[i]); System.out.println(headers[i]);
}
System.out.println("----------------------------------------");
if (entity != null) {
System.out.println(EntityUtils.toString(entity));
}
} finally {
response.close();
} }
System.out.println("----------------------------------------");
if (entity != null) {
System.out.println(EntityUtils.toString(entity));
}
} finally { } finally {
// When HttpClient instance is no longer needed, httpclient.close();
// shut down the connection manager to ensure
// immediate deallocation of all system resources
httpclient.getConnectionManager().shutdown();
} }
} }

View File

@ -31,13 +31,15 @@ import java.util.List;
import org.apache.http.Consts; import org.apache.http.Consts;
import org.apache.http.HttpEntity; import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair; import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost; import org.apache.http.client.methods.HttpPost;
import org.apache.http.cookie.Cookie; import org.apache.http.cookie.Cookie;
import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair; import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils; import org.apache.http.util.EntityUtils;
@ -48,59 +50,62 @@ import org.apache.http.util.EntityUtils;
public class ClientFormLogin { public class ClientFormLogin {
public static void main(String[] args) throws Exception { public static void main(String[] args) throws Exception {
BasicCookieStore cookieStore = new BasicCookieStore();
DefaultHttpClient httpclient = new DefaultHttpClient(); CloseableHttpClient httpclient = HttpClients.custom().setCookieStore(cookieStore).build();
try { try {
HttpGet httpget = new HttpGet("https://portal.sun.com/portal/dt"); HttpGet httpget = new HttpGet("https://portal.sun.com/portal/dt");
HttpResponse response = httpclient.execute(httpget); CloseableHttpResponse response1 = httpclient.execute(httpget);
HttpEntity entity = response.getEntity(); try {
HttpEntity entity = response1.getEntity();
System.out.println("Login form get: " + response.getStatusLine()); System.out.println("Login form get: " + response1.getStatusLine());
EntityUtils.consume(entity); EntityUtils.consume(entity);
System.out.println("Initial set of cookies:"); System.out.println("Initial set of cookies:");
List<Cookie> cookies = httpclient.getCookieStore().getCookies(); List<Cookie> cookies = cookieStore.getCookies();
if (cookies.isEmpty()) { if (cookies.isEmpty()) {
System.out.println("None"); System.out.println("None");
} else { } else {
for (int i = 0; i < cookies.size(); i++) { for (int i = 0; i < cookies.size(); i++) {
System.out.println("- " + cookies.get(i).toString()); System.out.println("- " + cookies.get(i).toString());
}
} }
} finally {
response1.close();
} }
HttpPost httpost = new HttpPost("https://portal.sun.com/amserver/UI/Login?" + HttpPost httpost = new HttpPost("https://portal.sun.com/amserver/UI/Login?" +
"org=self_registered_users&" + "org=self_registered_users&" +
"goto=/portal/dt&" + "goto=/portal/dt&" +
"gotoOnFail=/portal/dt?error=true"); "gotoOnFail=/portal/dt?error=true");
List <NameValuePair> nvps = new ArrayList <NameValuePair>(); List <NameValuePair> nvps = new ArrayList <NameValuePair>();
nvps.add(new BasicNameValuePair("IDToken1", "username")); nvps.add(new BasicNameValuePair("IDToken1", "username"));
nvps.add(new BasicNameValuePair("IDToken2", "password")); nvps.add(new BasicNameValuePair("IDToken2", "password"));
httpost.setEntity(new UrlEncodedFormEntity(nvps, Consts.UTF_8)); httpost.setEntity(new UrlEncodedFormEntity(nvps, Consts.UTF_8));
response = httpclient.execute(httpost); CloseableHttpResponse response2 = httpclient.execute(httpost);
entity = response.getEntity(); try {
HttpEntity entity = response2.getEntity();
System.out.println("Login form get: " + response.getStatusLine()); System.out.println("Login form get: " + response2.getStatusLine());
EntityUtils.consume(entity); EntityUtils.consume(entity);
System.out.println("Post logon cookies:"); System.out.println("Post logon cookies:");
cookies = httpclient.getCookieStore().getCookies(); List<Cookie> cookies = cookieStore.getCookies();
if (cookies.isEmpty()) { if (cookies.isEmpty()) {
System.out.println("None"); System.out.println("None");
} else { } else {
for (int i = 0; i < cookies.size(); i++) { for (int i = 0; i < cookies.size(); i++) {
System.out.println("- " + cookies.get(i).toString()); System.out.println("- " + cookies.get(i).toString());
}
} }
} finally {
response2.close();
} }
} finally { } finally {
// When HttpClient instance is no longer needed, httpclient.close();
// shut down the connection manager to ensure
// immediate deallocation of all system resources
httpclient.getConnectionManager().shutdown();
} }
} }
} }

View File

@ -38,8 +38,10 @@ import org.apache.http.HttpRequestInterceptor;
import org.apache.http.HttpResponse; import org.apache.http.HttpResponse;
import org.apache.http.HttpResponseInterceptor; import org.apache.http.HttpResponseInterceptor;
import org.apache.http.client.entity.GzipDecompressingEntity; import org.apache.http.client.entity.GzipDecompressingEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.protocol.HttpContext; import org.apache.http.protocol.HttpContext;
import org.apache.http.util.EntityUtils; import org.apache.http.util.EntityUtils;
@ -59,9 +61,8 @@ import org.apache.http.util.EntityUtils;
public class ClientGZipContentCompression { public class ClientGZipContentCompression {
public final static void main(String[] args) throws Exception { public final static void main(String[] args) throws Exception {
DefaultHttpClient httpclient = new DefaultHttpClient(); CloseableHttpClient httpclient = HttpClients.custom()
try { .addInterceptorFirst(new HttpRequestInterceptor() {
httpclient.addRequestInterceptor(new HttpRequestInterceptor() {
public void process( public void process(
final HttpRequest request, final HttpRequest request,
@ -69,11 +70,8 @@ public class ClientGZipContentCompression {
if (!request.containsHeader("Accept-Encoding")) { if (!request.containsHeader("Accept-Encoding")) {
request.addHeader("Accept-Encoding", "gzip"); request.addHeader("Accept-Encoding", "gzip");
} }
}
}); }}).addInterceptorFirst(new HttpResponseInterceptor() {
httpclient.addResponseInterceptor(new HttpResponseInterceptor() {
public void process( public void process(
final HttpResponse response, final HttpResponse response,
@ -94,34 +92,33 @@ public class ClientGZipContentCompression {
} }
} }
}); }).build();
try {
HttpGet httpget = new HttpGet("http://www.apache.org/"); HttpGet httpget = new HttpGet("http://www.apache.org/");
// Execute HTTP request // Execute HTTP request
System.out.println("executing request " + httpget.getURI()); System.out.println("executing request " + httpget.getURI());
HttpResponse response = httpclient.execute(httpget); CloseableHttpResponse response = httpclient.execute(httpget);
try {
System.out.println("----------------------------------------"); System.out.println("----------------------------------------");
System.out.println(response.getStatusLine()); System.out.println(response.getStatusLine());
System.out.println(response.getLastHeader("Content-Encoding")); System.out.println(response.getLastHeader("Content-Encoding"));
System.out.println(response.getLastHeader("Content-Length")); System.out.println(response.getLastHeader("Content-Length"));
System.out.println("----------------------------------------");
HttpEntity entity = response.getEntity();
if (entity != null) {
String content = EntityUtils.toString(entity);
System.out.println(content);
System.out.println("----------------------------------------"); System.out.println("----------------------------------------");
System.out.println("Uncompressed size: "+content.length());
}
HttpEntity entity = response.getEntity();
if (entity != null) {
String content = EntityUtils.toString(entity);
System.out.println(content);
System.out.println("----------------------------------------");
System.out.println("Uncompressed size: "+content.length());
}
} finally {
response.close();
}
} finally { } finally {
// When HttpClient instance is no longer needed, httpclient.close();
// shut down the connection manager to ensure
// immediate deallocation of all system resources
httpclient.getConnectionManager().shutdown();
} }
} }

View File

@ -30,16 +30,18 @@ import java.io.InputStreamReader;
import org.apache.http.HttpEntity; import org.apache.http.HttpEntity;
import org.apache.http.HttpHost; import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus; import org.apache.http.HttpStatus;
import org.apache.http.auth.AuthScheme; import org.apache.http.auth.AuthScheme;
import org.apache.http.auth.AuthScope; import org.apache.http.auth.AuthScope;
import org.apache.http.auth.AuthState; import org.apache.http.auth.AuthState;
import org.apache.http.auth.Credentials; import org.apache.http.auth.Credentials;
import org.apache.http.auth.UsernamePasswordCredentials; import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.protocol.ClientContext; import org.apache.http.client.protocol.ClientContext;
import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.protocol.BasicHttpContext; import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.ExecutionContext; import org.apache.http.protocol.ExecutionContext;
import org.apache.http.protocol.HttpContext; import org.apache.http.protocol.HttpContext;
@ -52,7 +54,9 @@ import org.apache.http.util.EntityUtils;
public class ClientInteractiveAuthentication { public class ClientInteractiveAuthentication {
public static void main(String[] args) throws Exception { public static void main(String[] args) throws Exception {
DefaultHttpClient httpclient = new DefaultHttpClient(); BasicCredentialsProvider credsProvider = new BasicCredentialsProvider();
CloseableHttpClient httpclient = HttpClients.custom()
.setCredentialsProvider(credsProvider).build();
try { try {
// Create local execution context // Create local execution context
HttpContext localContext = new BasicHttpContext(); HttpContext localContext = new BasicHttpContext();
@ -62,60 +66,59 @@ public class ClientInteractiveAuthentication {
boolean trying = true; boolean trying = true;
while (trying) { while (trying) {
System.out.println("executing request " + httpget.getRequestLine()); System.out.println("executing request " + httpget.getRequestLine());
HttpResponse response = httpclient.execute(httpget, localContext); CloseableHttpResponse response = httpclient.execute(httpget, localContext);
try {
System.out.println("----------------------------------------");
System.out.println(response.getStatusLine());
// Consume response content
HttpEntity entity = response.getEntity();
EntityUtils.consume(entity);
int sc = response.getStatusLine().getStatusCode();
AuthState authState = null;
HttpHost authhost = null;
if (sc == HttpStatus.SC_UNAUTHORIZED) {
// Target host authentication required
authState = (AuthState) localContext.getAttribute(ClientContext.TARGET_AUTH_STATE);
authhost = (HttpHost) localContext.getAttribute(ExecutionContext.HTTP_TARGET_HOST);
}
if (sc == HttpStatus.SC_PROXY_AUTHENTICATION_REQUIRED) {
// Proxy authentication required
authState = (AuthState) localContext.getAttribute(ClientContext.PROXY_AUTH_STATE);
authhost = (HttpHost) localContext.getAttribute(ExecutionContext.HTTP_PROXY_HOST);
}
if (authState != null) {
System.out.println("----------------------------------------"); System.out.println("----------------------------------------");
AuthScheme authscheme = authState.getAuthScheme(); System.out.println(response.getStatusLine());
System.out.println("Please provide credentials for " +
authscheme.getRealm() + "@" + authhost.toHostString());
BufferedReader console = new BufferedReader(new InputStreamReader(System.in)); // Consume response content
HttpEntity entity = response.getEntity();
EntityUtils.consume(entity);
System.out.print("Enter username: "); int sc = response.getStatusLine().getStatusCode();
String user = console.readLine();
System.out.print("Enter password: ");
String password = console.readLine();
if (user != null && user.length() > 0) { AuthState authState = null;
Credentials creds = new UsernamePasswordCredentials(user, password); HttpHost authhost = null;
httpclient.getCredentialsProvider().setCredentials(new AuthScope(authhost), creds); if (sc == HttpStatus.SC_UNAUTHORIZED) {
trying = true; // Target host authentication required
authState = (AuthState) localContext.getAttribute(ClientContext.TARGET_AUTH_STATE);
authhost = (HttpHost) localContext.getAttribute(ExecutionContext.HTTP_TARGET_HOST);
}
if (sc == HttpStatus.SC_PROXY_AUTHENTICATION_REQUIRED) {
// Proxy authentication required
authState = (AuthState) localContext.getAttribute(ClientContext.PROXY_AUTH_STATE);
authhost = (HttpHost) localContext.getAttribute(ExecutionContext.HTTP_PROXY_HOST);
}
if (authState != null) {
System.out.println("----------------------------------------");
AuthScheme authscheme = authState.getAuthScheme();
System.out.println("Please provide credentials for " +
authscheme.getRealm() + "@" + authhost.toHostString());
BufferedReader console = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter username: ");
String user = console.readLine();
System.out.print("Enter password: ");
String password = console.readLine();
if (user != null && user.length() > 0) {
Credentials creds = new UsernamePasswordCredentials(user, password);
credsProvider.setCredentials(new AuthScope(authhost), creds);
trying = true;
} else {
trying = false;
}
} else { } else {
trying = false; trying = false;
} }
} else { } finally {
trying = false; response.close();
} }
} }
} finally { } finally {
// When HttpClient instance is no longer needed, httpclient.close();
// shut down the connection manager to ensure
// immediate deallocation of all system resources
httpclient.getConnectionManager().shutdown();
} }
} }
} }

View File

@ -1,171 +0,0 @@
/*
* ====================================================================
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
package org.apache.http.examples.client;
import java.security.Principal;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.Credentials;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.client.params.AuthPolicy;
import org.apache.http.impl.auth.SPNegoSchemeFactory;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
/**
* SPNEGO (Kerberos) auth example.
*
* <p><b>Information</b></p>
* <p>For the best compatibility use Java >= 1.6 as it supports SPNEGO authentication more
completely.</p>
* <p><em>NegotiateSchemeFactory</em> kas two custom methods</p>
* <p><em>#setStripPort(boolean)</em> - default is false, with strip the port off the Kerberos
* service name if true. Found useful with JBoss Negotiation. Can be used with Java >= 1.5</p>
* <p><em>#setSpengoGenerator(SpnegoTokenGenerator)</em> - default is null, class to use to wrap
* kerberos token. An example is in contrib - <em>org.apache.http.contrib.auth.BouncySpnegoTokenGenerator</em>.
* Requires use of <a href="http://www.bouncycastle.org/java.html">bouncy castle libs</a>.
* Useful with Java 1.5.
* </p>
* <p><b>Addtional Config Files</b></p>
* <p>Two files control how Java uses/configures Kerberos. Very basic examples are below. There
* is a large amount of information on the web.</p>
* <p><a href="http://java.sun.com/j2se/1.5.0/docs/guide/security/jaas/spec/com/sun/security/auth/module/Krb5LoginModule.html">http://java.sun.com/j2se/1.5.0/docs/guide/security/jaas/spec/com/sun/security/auth/module/Krb5LoginModule.html</a>
* <p><b>krb5.conf</b></p>
* <pre>
* [libdefaults]
* default_realm = AD.EXAMPLE.NET
* udp_preference_limit = 1
* [realms]
* AD.EXAMPLE.NET = {
* kdc = AD.EXAMPLE.NET
* }
* DEV.EXAMPLE.NET = {
* kdc = DEV.EXAMPLE.NET
* }
* [domain_realms]
* .ad.example.net = AD.EXAMPLE.NET
* ad.example.net = AD.EXAMPLE.NET
* .dev.example.net = DEV.EXAMPLE.NET
* dev.example.net = DEV.EXAMPLE.NET
* gb.dev.example.net = DEV.EXAMPLE.NET
* .gb.dev.example.net = DEV.EXAMPLE.NET
* </pre>
* <b>login.conf</b>
* <pre>
*com.sun.security.jgss.login {
* com.sun.security.auth.module.Krb5LoginModule required client=TRUE useTicketCache=true debug=true;
*};
*
*com.sun.security.jgss.initiate {
* com.sun.security.auth.module.Krb5LoginModule required client=TRUE useTicketCache=true debug=true;
*};
*
*com.sun.security.jgss.accept {
* com.sun.security.auth.module.Krb5LoginModule required client=TRUE useTicketCache=true debug=true;
*};
* </pre>
* <p><b>Windows specific configuration</b></p>
* <p>
* The registry key <em>allowtgtsessionkey</em> should be added, and set correctly, to allow
* session keys to be sent in the Kerberos Ticket-Granting Ticket.
* </p>
* <p>
* On the Windows Server 2003 and Windows 2000 SP4, here is the required registry setting:
* </p>
* <pre>
* HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\Lsa\Kerberos\Parameters
* Value Name: allowtgtsessionkey
* Value Type: REG_DWORD
* Value: 0x01
* </pre>
* <p>
* Here is the location of the registry setting on Windows XP SP2:
* </p>
* <pre>
* HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\Lsa\Kerberos\
* Value Name: allowtgtsessionkey
* Value Type: REG_DWORD
* Value: 0x01
* </pre>
*
* @since 4.1
*/
public class ClientKerberosAuthentication {
public static void main(String[] args) throws Exception {
System.setProperty("java.security.auth.login.config", "login.conf");
System.setProperty("java.security.krb5.conf", "krb5.conf");
System.setProperty("sun.security.krb5.debug", "true");
System.setProperty("javax.security.auth.useSubjectCredsOnly","false");
DefaultHttpClient httpclient = new DefaultHttpClient();
try {
httpclient.getAuthSchemes().register(AuthPolicy.SPNEGO, new SPNegoSchemeFactory());
Credentials use_jaas_creds = new Credentials() {
public String getPassword() {
return null;
}
public Principal getUserPrincipal() {
return null;
}
};
httpclient.getCredentialsProvider().setCredentials(
new AuthScope(null, -1, null),
use_jaas_creds);
HttpUriRequest request = new HttpGet("http://kerberoshost/");
HttpResponse response = httpclient.execute(request);
HttpEntity entity = response.getEntity();
System.out.println("----------------------------------------");
System.out.println(response.getStatusLine());
System.out.println("----------------------------------------");
if (entity != null) {
System.out.println(EntityUtils.toString(entity));
}
System.out.println("----------------------------------------");
// This ensures the connection gets released back to the manager
EntityUtils.consume(entity);
} finally {
// When HttpClient instance is no longer needed,
// shut down the connection manager to ensure
// immediate deallocation of all system resources
httpclient.getConnectionManager().shutdown();
}
}
}

View File

@ -27,11 +27,11 @@
package org.apache.http.examples.client; package org.apache.http.examples.client;
import org.apache.http.HttpEntity; import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse; import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.conn.PoolingClientConnectionManager; import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.protocol.BasicHttpContext; import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext; import org.apache.http.protocol.HttpContext;
import org.apache.http.util.EntityUtils; import org.apache.http.util.EntityUtils;
@ -46,10 +46,10 @@ public class ClientMultiThreadedExecution {
// 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.
PoolingClientConnectionManager cm = new PoolingClientConnectionManager(); PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
cm.setMaxTotal(100); cm.setMaxTotal(100);
HttpClient httpclient = new DefaultHttpClient(cm); CloseableHttpClient httpclient = HttpClients.custom().setConnectionManager(cm).build();
try { try {
// create an array of URIs to perform GETs on // create an array of URIs to perform GETs on
String[] urisToGet = { String[] urisToGet = {
@ -77,10 +77,7 @@ public class ClientMultiThreadedExecution {
} }
} finally { } finally {
// When HttpClient instance is no longer needed, httpclient.close();
// shut down the connection manager to ensure
// immediate deallocation of all system resources
httpclient.getConnectionManager().shutdown();
} }
} }
@ -89,12 +86,12 @@ public class ClientMultiThreadedExecution {
*/ */
static class GetThread extends Thread { static class GetThread extends Thread {
private final HttpClient httpClient; private final CloseableHttpClient httpClient;
private final HttpContext context; private final HttpContext context;
private final HttpGet httpget; private final HttpGet httpget;
private final int id; private final int id;
public GetThread(HttpClient httpClient, HttpGet httpget, int id) { public GetThread(CloseableHttpClient httpClient, HttpGet httpget, int id) {
this.httpClient = httpClient; this.httpClient = httpClient;
this.context = new BasicHttpContext(); this.context = new BasicHttpContext();
this.httpget = httpget; this.httpget = httpget;
@ -106,24 +103,21 @@ public class ClientMultiThreadedExecution {
*/ */
@Override @Override
public void run() { public void run() {
System.out.println(id + " - about to get something from " + httpget.getURI());
try { try {
System.out.println(id + " - about to get something from " + httpget.getURI());
// execute the method CloseableHttpResponse response = httpClient.execute(httpget, context);
HttpResponse response = httpClient.execute(httpget, context); try {
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();
HttpEntity entity = response.getEntity(); if (entity != null) {
if (entity != null) { byte[] bytes = EntityUtils.toByteArray(entity);
byte[] bytes = EntityUtils.toByteArray(entity); System.out.println(id + " - " + bytes.length + " bytes read");
System.out.println(id + " - " + bytes.length + " bytes read"); }
} finally {
response.close();
} }
} catch (Exception e) { } catch (Exception e) {
httpget.abort();
System.out.println(id + " - error: " + e); System.out.println(id + " - error: " + e);
} }
} }

View File

@ -27,15 +27,18 @@ package org.apache.http.examples.client;
import org.apache.http.HttpEntity; import org.apache.http.HttpEntity;
import org.apache.http.HttpHost; import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.auth.AuthScope; import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials; import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.AuthCache; import org.apache.http.client.AuthCache;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.protocol.ClientContext; import org.apache.http.client.protocol.ClientContext;
import org.apache.http.impl.auth.BasicScheme; import org.apache.http.impl.auth.BasicScheme;
import org.apache.http.impl.client.BasicAuthCache; import org.apache.http.impl.client.BasicAuthCache;
import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.protocol.BasicHttpContext; import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.util.EntityUtils; import org.apache.http.util.EntityUtils;
@ -50,14 +53,14 @@ import org.apache.http.util.EntityUtils;
public class ClientPreemptiveBasicAuthentication { public class ClientPreemptiveBasicAuthentication {
public static void main(String[] args) throws Exception { public static void main(String[] args) throws Exception {
HttpHost targetHost = new HttpHost("localhost", 80, "http"); HttpHost targetHost = new HttpHost("localhost", 80, "http");
CredentialsProvider credsProvider = new BasicCredentialsProvider();
DefaultHttpClient httpclient = new DefaultHttpClient(); credsProvider.setCredentials(
new AuthScope(targetHost.getHostName(), targetHost.getPort()),
new UsernamePasswordCredentials("username", "password"));
CloseableHttpClient httpclient = HttpClients.custom()
.setCredentialsProvider(credsProvider).build();
try { try {
httpclient.getCredentialsProvider().setCredentials(
new AuthScope(targetHost.getHostName(), targetHost.getPort()),
new UsernamePasswordCredentials("username", "password"));
// Create AuthCache instance // Create AuthCache instance
AuthCache authCache = new BasicAuthCache(); AuthCache authCache = new BasicAuthCache();
@ -76,22 +79,22 @@ public class ClientPreemptiveBasicAuthentication {
System.out.println("to target: " + targetHost); System.out.println("to target: " + targetHost);
for (int i = 0; i < 3; i++) { for (int i = 0; i < 3; i++) {
HttpResponse response = httpclient.execute(targetHost, httpget, localcontext); CloseableHttpResponse response = httpclient.execute(targetHost, httpget, localcontext);
HttpEntity entity = response.getEntity(); try {
HttpEntity entity = response.getEntity();
System.out.println("----------------------------------------"); System.out.println("----------------------------------------");
System.out.println(response.getStatusLine()); System.out.println(response.getStatusLine());
if (entity != null) { if (entity != null) {
System.out.println("Response content length: " + entity.getContentLength()); System.out.println("Response content length: " + entity.getContentLength());
}
EntityUtils.consume(entity);
} finally {
response.close();
} }
EntityUtils.consume(entity);
} }
} finally { } finally {
// When HttpClient instance is no longer needed, httpclient.close();
// shut down the connection manager to ensure
// immediate deallocation of all system resources
httpclient.getConnectionManager().shutdown();
} }
} }

View File

@ -27,22 +27,25 @@ package org.apache.http.examples.client;
import org.apache.http.HttpEntity; import org.apache.http.HttpEntity;
import org.apache.http.HttpHost; import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.auth.AuthScope; import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials; import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.AuthCache; import org.apache.http.client.AuthCache;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.protocol.ClientContext; import org.apache.http.client.protocol.ClientContext;
import org.apache.http.impl.auth.DigestScheme; import org.apache.http.impl.auth.DigestScheme;
import org.apache.http.impl.client.BasicAuthCache; import org.apache.http.impl.client.BasicAuthCache;
import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.protocol.BasicHttpContext; import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.util.EntityUtils; import org.apache.http.util.EntityUtils;
/** /**
* An example of HttpClient can be customized to authenticate * An example of HttpClient can be customized to authenticate
* preemptively using DIGEST scheme. * preemptively using DIGEST scheme.
* <b/> * <p/>
* Generally, preemptive authentication can be considered less * Generally, preemptive authentication can be considered less
* secure than a response to an authentication challenge * secure than a response to an authentication challenge
* and therefore discouraged. * and therefore discouraged.
@ -50,14 +53,14 @@ import org.apache.http.util.EntityUtils;
public class ClientPreemptiveDigestAuthentication { public class ClientPreemptiveDigestAuthentication {
public static void main(String[] args) throws Exception { public static void main(String[] args) throws Exception {
HttpHost targetHost = new HttpHost("localhost", 80, "http"); HttpHost targetHost = new HttpHost("localhost", 80, "http");
CredentialsProvider credsProvider = new BasicCredentialsProvider();
DefaultHttpClient httpclient = new DefaultHttpClient(); credsProvider.setCredentials(
new AuthScope(targetHost.getHostName(), targetHost.getPort()),
new UsernamePasswordCredentials("username", "password"));
CloseableHttpClient httpclient = HttpClients.custom()
.setCredentialsProvider(credsProvider).build();
try { try {
httpclient.getCredentialsProvider().setCredentials(
new AuthScope(targetHost.getHostName(), targetHost.getPort()),
new UsernamePasswordCredentials("username", "password"));
// Create AuthCache instance // Create AuthCache instance
AuthCache authCache = new BasicAuthCache(); AuthCache authCache = new BasicAuthCache();
@ -80,22 +83,22 @@ public class ClientPreemptiveDigestAuthentication {
System.out.println("to target: " + targetHost); System.out.println("to target: " + targetHost);
for (int i = 0; i < 3; i++) { for (int i = 0; i < 3; i++) {
HttpResponse response = httpclient.execute(targetHost, httpget, localcontext); CloseableHttpResponse response = httpclient.execute(targetHost, httpget, localcontext);
HttpEntity entity = response.getEntity(); try {
HttpEntity entity = response.getEntity();
System.out.println("----------------------------------------"); System.out.println("----------------------------------------");
System.out.println(response.getStatusLine()); System.out.println(response.getStatusLine());
if (entity != null) { if (entity != null) {
System.out.println("Response content length: " + entity.getContentLength()); System.out.println("Response content length: " + entity.getContentLength());
}
EntityUtils.consume(entity);
} finally {
response.close();
} }
EntityUtils.consume(entity);
} }
} finally { } finally {
// When HttpClient instance is no longer needed, httpclient.close();
// shut down the connection manager to ensure
// immediate deallocation of all system resources
httpclient.getConnectionManager().shutdown();
} }
} }

View File

@ -27,12 +27,15 @@ package org.apache.http.examples.client;
import org.apache.http.HttpEntity; import org.apache.http.HttpEntity;
import org.apache.http.HttpHost; import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.auth.AuthScope; import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials; import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.params.ConnRoutePNames; import org.apache.http.conn.params.ConnRoutePNames;
import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils; import org.apache.http.util.EntityUtils;
/** /**
@ -42,13 +45,13 @@ import org.apache.http.util.EntityUtils;
public class ClientProxyAuthentication { public class ClientProxyAuthentication {
public static void main(String[] args) throws Exception { public static void main(String[] args) throws Exception {
CredentialsProvider credsProvider = new BasicCredentialsProvider();
DefaultHttpClient httpclient = new DefaultHttpClient(); credsProvider.setCredentials(
new AuthScope("localhost", 8080),
new UsernamePasswordCredentials("username", "password"));
CloseableHttpClient httpclient = HttpClients.custom()
.setCredentialsProvider(credsProvider).build();
try { try {
httpclient.getCredentialsProvider().setCredentials(
new AuthScope("localhost", 8080),
new UsernamePasswordCredentials("username", "password"));
HttpHost targetHost = new HttpHost("www.verisign.com", 443, "https"); HttpHost targetHost = new HttpHost("www.verisign.com", 443, "https");
HttpHost proxy = new HttpHost("localhost", 8080); HttpHost proxy = new HttpHost("localhost", 8080);
@ -60,21 +63,21 @@ public class ClientProxyAuthentication {
System.out.println("via proxy: " + proxy); System.out.println("via proxy: " + proxy);
System.out.println("to target: " + targetHost); System.out.println("to target: " + targetHost);
HttpResponse response = httpclient.execute(targetHost, httpget); CloseableHttpResponse response = httpclient.execute(targetHost, httpget);
HttpEntity entity = response.getEntity(); try {
HttpEntity entity = response.getEntity();
System.out.println("----------------------------------------"); System.out.println("----------------------------------------");
System.out.println(response.getStatusLine()); System.out.println(response.getStatusLine());
if (entity != null) { if (entity != null) {
System.out.println("Response content length: " + entity.getContentLength()); System.out.println("Response content length: " + entity.getContentLength());
}
EntityUtils.consume(entity);
} finally {
response.close();
} }
EntityUtils.consume(entity);
} finally { } finally {
// When HttpClient instance is no longer needed, httpclient.close();
// shut down the connection manager to ensure
// immediate deallocation of all system resources
httpclient.getConnectionManager().shutdown();
} }
} }
} }

View File

@ -28,10 +28,10 @@
package org.apache.http.examples.client; package org.apache.http.examples.client;
import org.apache.http.client.ResponseHandler; import org.apache.http.client.ResponseHandler;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.BasicResponseHandler; import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
/** /**
* This example demonstrates the use of the {@link ResponseHandler} to simplify * This example demonstrates the use of the {@link ResponseHandler} to simplify
@ -40,8 +40,7 @@ import org.apache.http.impl.client.DefaultHttpClient;
public class ClientWithResponseHandler { public class ClientWithResponseHandler {
public final static void main(String[] args) throws Exception { public final static void main(String[] args) throws Exception {
CloseableHttpClient httpclient = HttpClients.createDefault();
HttpClient httpclient = new DefaultHttpClient();
try { try {
HttpGet httpget = new HttpGet("http://www.google.com/"); HttpGet httpget = new HttpGet("http://www.google.com/");
@ -55,10 +54,7 @@ public class ClientWithResponseHandler {
System.out.println("----------------------------------------"); System.out.println("----------------------------------------");
} finally { } finally {
// When HttpClient instance is no longer needed, httpclient.close();
// shut down the connection manager to ensure
// immediate deallocation of all system resources
httpclient.getConnectionManager().shutdown();
} }
} }

View File

@ -30,54 +30,57 @@ import java.util.ArrayList;
import java.util.List; import java.util.List;
import org.apache.http.HttpEntity; import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair; import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost; import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair; import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils; import org.apache.http.util.EntityUtils;
public class QuickStart { public class QuickStart {
public static void main(String[] args) throws Exception { public static void main(String[] args) throws Exception {
DefaultHttpClient httpclient = new DefaultHttpClient(); CloseableHttpClient httpclient = HttpClients.createDefault();
HttpGet httpGet = new HttpGet("http://targethost/homepage");
HttpResponse response1 = httpclient.execute(httpGet);
// 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
// the user MUST either fully consume the response content or abort request
// execution by calling HttpGet#releaseConnection().
try { try {
System.out.println(response1.getStatusLine()); HttpGet httpGet = new HttpGet("http://targethost/homepage");
HttpEntity entity1 = response1.getEntity(); CloseableHttpResponse response1 = httpclient.execute(httpGet);
// do something useful with the response body // The underlying HTTP connection is still held by the response object
// and ensure it is fully consumed // to allow the response content to be streamed directly from the network socket.
EntityUtils.consume(entity1); // In order to ensure correct deallocation of system resources
} finally { // the user MUST either fully consume the response content or abort request
httpGet.releaseConnection(); // execution by calling CloseableHttpResponse#close().
}
HttpPost httpPost = new HttpPost("http://targethost/login"); try {
List <NameValuePair> nvps = new ArrayList <NameValuePair>(); System.out.println(response1.getStatusLine());
nvps.add(new BasicNameValuePair("username", "vip")); HttpEntity entity1 = response1.getEntity();
nvps.add(new BasicNameValuePair("password", "secret")); // do something useful with the response body
httpPost.setEntity(new UrlEncodedFormEntity(nvps)); // and ensure it is fully consumed
HttpResponse response2 = httpclient.execute(httpPost); EntityUtils.consume(entity1);
} finally {
response1.close();
}
try { HttpPost httpPost = new HttpPost("http://targethost/login");
System.out.println(response2.getStatusLine()); List <NameValuePair> nvps = new ArrayList <NameValuePair>();
HttpEntity entity2 = response2.getEntity(); nvps.add(new BasicNameValuePair("username", "vip"));
// do something useful with the response body nvps.add(new BasicNameValuePair("password", "secret"));
// and ensure it is fully consumed httpPost.setEntity(new UrlEncodedFormEntity(nvps));
EntityUtils.consume(entity2); CloseableHttpResponse response2 = httpclient.execute(httpPost);
try {
System.out.println(response2.getStatusLine());
HttpEntity entity2 = response2.getEntity();
// do something useful with the response body
// and ensure it is fully consumed
EntityUtils.consume(entity2);
} finally {
response2.close();
}
} finally { } finally {
httpPost.releaseConnection(); httpclient.close();
} }
} }

View File

@ -34,6 +34,7 @@ import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse; import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpUriRequest; import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.conn.ClientConnectionManager; import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.impl.client.builder.HttpClientBuilder;
import org.apache.http.params.HttpParams; import org.apache.http.params.HttpParams;
import org.apache.http.protocol.HttpContext; import org.apache.http.protocol.HttpContext;
@ -47,7 +48,7 @@ import org.apache.http.protocol.HttpContext;
* <p/> * <p/>
* The usual execution flow can be demonstrated by the code snippet below: * The usual execution flow can be demonstrated by the code snippet below:
* <PRE> * <PRE>
* HttpClient httpclient = new DefaultHttpClient(); * MinimalHttpClient httpclient = HttpClientBuilder.buildDefault();
* *
* // Prepare a request object * // Prepare a request object
* HttpGet httpget = new HttpGet("http://www.apache.org/"); * HttpGet httpget = new HttpGet("http://www.apache.org/");
@ -93,15 +94,15 @@ import org.apache.http.protocol.HttpContext;
* *
* } * }
* *
* // When HttpClient instance is no longer needed, * // When HttpClient instance is no longer needed, it can be closed
* // shut down the connection manager to ensure * // to ensure immediate deallocation of all system resources
* // immediate deallocation of all system resources * httpclient.close();
* httpclient.getConnectionManager().shutdown();
* } * }
* </PRE> * </PRE>
* *
* @since 4.0 * @since 4.0
*/ */
@SuppressWarnings("deprecation")
public interface HttpClient { public interface HttpClient {
@ -119,7 +120,10 @@ public interface HttpClient {
* Obtains the connection manager used by this client. * Obtains the connection manager used by this client.
* *
* @return the connection manager * @return the connection manager
*
* @deprecated (4.3) use {@link HttpClientBuilder}.
*/ */
@Deprecated
ClientConnectionManager getConnectionManager(); ClientConnectionManager getConnectionManager();
/** /**

View File

@ -0,0 +1,40 @@
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.client.methods;
import java.io.Closeable;
import org.apache.http.HttpResponse;
/**
* Extended version of the {@link HttpResponse} interface that also extends {@link Closeable}.
*
* @since 4.3
*/
public interface CloseableHttpResponse extends HttpResponse, Closeable {
}

View File

@ -34,7 +34,7 @@ import org.apache.http.client.HttpClient;
import org.apache.http.util.EntityUtils; import org.apache.http.util.EntityUtils;
/** /**
* Static helpers for dealing with {@link HttpResponse}s and {@link HttpClient}s. * Static helpers for dealing with {@link HttpResponse}s.
* *
* @since 4.2 * @since 4.2
*/ */
@ -97,7 +97,10 @@ public class HttpClientUtils {
* @param httpClient * @param httpClient
* the HttpClient to close, may be null or already closed. * the HttpClient to close, may be null or already closed.
* @since 4.2 * @since 4.2
*
* @deprecated (4.3) do not use.
*/ */
@Deprecated
public static void closeQuietly(final HttpClient httpClient) { public static void closeQuietly(final HttpClient httpClient) {
if (httpClient != null) { if (httpClient != null) {
httpClient.getConnectionManager().shutdown(); httpClient.getConnectionManager().shutdown();

View File

@ -37,7 +37,6 @@ import org.apache.http.HttpException;
import org.apache.http.HttpHost; import org.apache.http.HttpHost;
import org.apache.http.HttpRequest; import org.apache.http.HttpRequest;
import org.apache.http.HttpRequestInterceptor; import org.apache.http.HttpRequestInterceptor;
import org.apache.http.HttpResponse;
import org.apache.http.HttpResponseInterceptor; import org.apache.http.HttpResponseInterceptor;
import org.apache.http.annotation.GuardedBy; import org.apache.http.annotation.GuardedBy;
import org.apache.http.annotation.ThreadSafe; import org.apache.http.annotation.ThreadSafe;
@ -55,6 +54,7 @@ import org.apache.http.client.RedirectHandler;
import org.apache.http.client.RedirectStrategy; import org.apache.http.client.RedirectStrategy;
import org.apache.http.client.RequestDirector; import org.apache.http.client.RequestDirector;
import org.apache.http.client.UserTokenHandler; import org.apache.http.client.UserTokenHandler;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.params.AuthPolicy; import org.apache.http.client.params.AuthPolicy;
import org.apache.http.client.params.ClientPNames; import org.apache.http.client.params.ClientPNames;
import org.apache.http.client.params.CookiePolicy; import org.apache.http.client.params.CookiePolicy;
@ -72,6 +72,7 @@ import org.apache.http.impl.auth.DigestSchemeFactory;
import org.apache.http.impl.auth.KerberosSchemeFactory; import org.apache.http.impl.auth.KerberosSchemeFactory;
import org.apache.http.impl.auth.NTLMSchemeFactory; import org.apache.http.impl.auth.NTLMSchemeFactory;
import org.apache.http.impl.auth.SPNegoSchemeFactory; import org.apache.http.impl.auth.SPNegoSchemeFactory;
import org.apache.http.impl.client.builder.HttpClientBuilder;
import org.apache.http.impl.conn.BasicClientConnectionManager; import org.apache.http.impl.conn.BasicClientConnectionManager;
import org.apache.http.impl.conn.DefaultHttpRoutePlanner; import org.apache.http.impl.conn.DefaultHttpRoutePlanner;
import org.apache.http.impl.conn.SchemeRegistryFactory; import org.apache.http.impl.conn.SchemeRegistryFactory;
@ -178,7 +179,7 @@ import org.apache.http.protocol.ImmutableHttpProcessor;
*/ */
@ThreadSafe @ThreadSafe
@Deprecated @Deprecated
public abstract class AbstractHttpClient extends AbstractBasicHttpClient { public abstract class AbstractHttpClient extends CloseableHttpClient {
private final Log log = LogFactory.getLog(getClass()); private final Log log = LogFactory.getLog(getClass());
@ -775,7 +776,7 @@ public abstract class AbstractHttpClient extends AbstractBasicHttpClient {
protocolProcessor = null; protocolProcessor = null;
} }
public final HttpResponse execute(HttpHost target, HttpRequest request, public final CloseableHttpResponse execute(HttpHost target, HttpRequest request,
HttpContext context) HttpContext context)
throws IOException, ClientProtocolException { throws IOException, ClientProtocolException {
@ -828,9 +829,10 @@ public abstract class AbstractHttpClient extends AbstractBasicHttpClient {
ClientPNames.DEFAULT_HOST); ClientPNames.DEFAULT_HOST);
HttpRoute route = routePlanner.determineRoute(targetForRoute, request, execContext); HttpRoute route = routePlanner.determineRoute(targetForRoute, request, execContext);
HttpResponse out; CloseableHttpResponse out;
try { try {
out = director.execute(target, request, execContext); out = CloseableHttpResponseProxy.newProxy(
director.execute(target, request, execContext));
} catch (RuntimeException re) { } catch (RuntimeException re) {
if (connectionBackoffStrategy.shouldBackoff(re)) { if (connectionBackoffStrategy.shouldBackoff(re)) {
backoffManager.backOff(route); backoffManager.backOff(route);
@ -851,7 +853,8 @@ public abstract class AbstractHttpClient extends AbstractBasicHttpClient {
} }
return out; return out;
} else { } else {
return director.execute(target, request, execContext); return CloseableHttpResponseProxy.newProxy(
director.execute(target, request, execContext));
} }
} catch(HttpException httpException) { } catch(HttpException httpException) {
throw new ClientProtocolException(httpException); throw new ClientProtocolException(httpException);
@ -976,4 +979,9 @@ public abstract class AbstractHttpClient extends AbstractBasicHttpClient {
(null, getParams(), req.getParams(), null); (null, getParams(), req.getParams(), null);
} }
public void close() {
getConnectionManager().shutdown();
}
} }

View File

@ -42,6 +42,7 @@ import org.apache.http.client.ResponseHandler;
import org.apache.http.client.ServiceUnavailableRetryStrategy; import org.apache.http.client.ServiceUnavailableRetryStrategy;
import org.apache.http.client.methods.HttpUriRequest; import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.conn.ClientConnectionManager; import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.impl.client.builder.HttpClientBuilder;
import org.apache.http.params.HttpParams; import org.apache.http.params.HttpParams;
import org.apache.http.protocol.HttpContext; import org.apache.http.protocol.HttpContext;
import org.apache.http.util.EntityUtils; import org.apache.http.util.EntityUtils;

View File

@ -27,6 +27,7 @@
package org.apache.http.impl.client; package org.apache.http.impl.client;
import java.io.Closeable;
import java.io.IOException; import java.io.IOException;
import java.lang.reflect.UndeclaredThrowableException; import java.lang.reflect.UndeclaredThrowableException;
import java.net.URI; import java.net.URI;
@ -41,20 +42,26 @@ import org.apache.http.annotation.ThreadSafe;
import org.apache.http.client.ClientProtocolException; import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient; import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler; import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpUriRequest; import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.client.utils.URIUtils; import org.apache.http.client.utils.URIUtils;
import org.apache.http.protocol.HttpContext; import org.apache.http.protocol.HttpContext;
import org.apache.http.util.EntityUtils; import org.apache.http.util.EntityUtils;
/** /**
* Minimal implementation of {@link HttpClient} that also implements {@link Closeable}.
*
* @since 4.3 * @since 4.3
*/ */
@ThreadSafe @ThreadSafe
public abstract class AbstractBasicHttpClient implements HttpClient { public abstract class CloseableHttpClient implements HttpClient, Closeable {
private final Log log = LogFactory.getLog(getClass()); private final Log log = LogFactory.getLog(getClass());
public HttpResponse execute( public abstract CloseableHttpResponse execute(HttpHost target, HttpRequest request,
HttpContext context) throws IOException, ClientProtocolException;
public CloseableHttpResponse execute(
final HttpUriRequest request, final HttpUriRequest request,
final HttpContext context) throws IOException, ClientProtocolException { final HttpContext context) throws IOException, ClientProtocolException {
if (request == null) { if (request == null) {
@ -79,12 +86,12 @@ public abstract class AbstractBasicHttpClient implements HttpClient {
return target; return target;
} }
public HttpResponse execute( public CloseableHttpResponse execute(
final HttpUriRequest request) throws IOException, ClientProtocolException { final HttpUriRequest request) throws IOException, ClientProtocolException {
return execute(request, (HttpContext) null); return execute(request, (HttpContext) null);
} }
public HttpResponse execute( public CloseableHttpResponse execute(
final HttpHost target, final HttpHost target,
final HttpRequest request) throws IOException, ClientProtocolException { final HttpRequest request) throws IOException, ClientProtocolException {
return execute(target, request, (HttpContext) null); return execute(target, request, (HttpContext) null);

View File

@ -0,0 +1,87 @@
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.impl.client;
import java.io.IOException;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.annotation.NotThreadSafe;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.util.EntityUtils;
/**
* @since 4.3
*/
@NotThreadSafe
class CloseableHttpResponseProxy implements InvocationHandler {
private final HttpResponse original;
CloseableHttpResponseProxy(final HttpResponse original) {
super();
this.original = original;
}
public void close() throws IOException {
HttpEntity entity = this.original.getEntity();
EntityUtils.consume(entity);
}
public Object invoke(
final Object proxy, final Method method, final Object[] args) throws Throwable {
String mname = method.getName();
if (mname.equals("close")) {
close();
return null;
} else {
try {
return method.invoke(original, args);
} catch (InvocationTargetException ex) {
Throwable cause = ex.getCause();
if (cause != null) {
throw cause;
} else {
throw ex;
}
}
}
}
public static CloseableHttpResponse newProxy(final HttpResponse original) {
return (CloseableHttpResponse) Proxy.newProxyInstance(
CloseableHttpResponseProxy.class.getClassLoader(),
new Class<?>[] { CloseableHttpResponse.class },
new CloseableHttpResponseProxy(original));
}
}

View File

@ -31,6 +31,7 @@ import org.apache.http.client.HttpClient;
import org.apache.http.client.protocol.RequestAcceptEncoding; import org.apache.http.client.protocol.RequestAcceptEncoding;
import org.apache.http.client.protocol.ResponseContentEncoding; import org.apache.http.client.protocol.ResponseContentEncoding;
import org.apache.http.conn.ClientConnectionManager; import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.impl.client.builder.HttpClientBuilder;
import org.apache.http.params.HttpParams; import org.apache.http.params.HttpParams;
import org.apache.http.protocol.BasicHttpProcessor; import org.apache.http.protocol.BasicHttpProcessor;

View File

@ -44,6 +44,7 @@ import org.apache.http.client.protocol.RequestAcceptEncoding;
import org.apache.http.client.protocol.ResponseContentEncoding; import org.apache.http.client.protocol.ResponseContentEncoding;
import org.apache.http.client.utils.URIUtils; import org.apache.http.client.utils.URIUtils;
import org.apache.http.conn.ClientConnectionManager; import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.impl.client.builder.HttpClientBuilder;
import org.apache.http.params.HttpParams; import org.apache.http.params.HttpParams;
import org.apache.http.protocol.BasicHttpContext; import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext; import org.apache.http.protocol.HttpContext;

View File

@ -38,6 +38,7 @@ import org.apache.http.client.protocol.RequestProxyAuthentication;
import org.apache.http.client.protocol.RequestTargetAuthentication; import org.apache.http.client.protocol.RequestTargetAuthentication;
import org.apache.http.client.protocol.ResponseProcessCookies; import org.apache.http.client.protocol.ResponseProcessCookies;
import org.apache.http.conn.ClientConnectionManager; import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.impl.client.builder.HttpClientBuilder;
import org.apache.http.params.CoreConnectionPNames; import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.params.CoreProtocolPNames; import org.apache.http.params.CoreProtocolPNames;
import org.apache.http.params.HttpConnectionParams; import org.apache.http.params.HttpConnectionParams;

View File

@ -33,7 +33,6 @@ import java.io.OutputStream;
import org.apache.http.annotation.NotThreadSafe; import org.apache.http.annotation.NotThreadSafe;
import org.apache.http.entity.HttpEntityWrapper; import org.apache.http.entity.HttpEntityWrapper;
import org.apache.http.impl.client.exec.HttpRequestWrapper;
import org.apache.http.Header; import org.apache.http.Header;
import org.apache.http.HttpEntity; import org.apache.http.HttpEntity;
@ -51,7 +50,7 @@ import org.apache.http.protocol.HTTP;
* *
* @since 4.0 * @since 4.0
* *
* @deprecated (4.3) use {@link HttpRequestWrapper}. * @deprecated (4.3) do not use.
*/ */
@Deprecated @Deprecated
@NotThreadSafe // e.g. [gs]etEntity() @NotThreadSafe // e.g. [gs]etEntity()

View File

@ -0,0 +1,51 @@
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.impl.client;
import org.apache.http.annotation.Immutable;
import org.apache.http.impl.client.builder.HttpClientBuilder;
/**
* @since 4.3
*/
@Immutable
public class HttpClients {
private HttpClients() {
super();
}
public static HttpClientBuilder custom() {
return HttpClientBuilder.create();
}
public static CloseableHttpClient createDefault() {
return HttpClientBuilder.create().build();
}
}

View File

@ -37,7 +37,6 @@ import org.apache.http.ProtocolException;
import org.apache.http.ProtocolVersion; import org.apache.http.ProtocolVersion;
import org.apache.http.RequestLine; import org.apache.http.RequestLine;
import org.apache.http.client.methods.HttpUriRequest; import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.impl.client.exec.HttpRequestWrapper;
import org.apache.http.message.AbstractHttpMessage; import org.apache.http.message.AbstractHttpMessage;
import org.apache.http.message.BasicRequestLine; import org.apache.http.message.BasicRequestLine;
import org.apache.http.params.HttpProtocolParams; import org.apache.http.params.HttpProtocolParams;
@ -52,7 +51,7 @@ import org.apache.http.params.HttpProtocolParams;
* *
* @since 4.0 * @since 4.0
* *
* @deprecated (4.3) use {@link HttpRequestWrapper}. * @deprecated (4.3) do not use.
*/ */
@NotThreadSafe @NotThreadSafe
@Deprecated @Deprecated

View File

@ -35,6 +35,7 @@ import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.routing.HttpRoutePlanner; import org.apache.http.conn.routing.HttpRoutePlanner;
import org.apache.http.impl.DefaultConnectionReuseStrategy; import org.apache.http.impl.DefaultConnectionReuseStrategy;
import org.apache.http.impl.NoConnectionReuseStrategy; import org.apache.http.impl.NoConnectionReuseStrategy;
import org.apache.http.impl.client.builder.HttpClientBuilder;
import org.apache.http.impl.conn.PoolingClientConnectionManager; import org.apache.http.impl.conn.PoolingClientConnectionManager;
import org.apache.http.impl.conn.ProxySelectorRoutePlanner; import org.apache.http.impl.conn.ProxySelectorRoutePlanner;
import org.apache.http.impl.conn.SchemeRegistryFactory; import org.apache.http.impl.conn.SchemeRegistryFactory;

View File

@ -25,7 +25,7 @@
* *
*/ */
package org.apache.http.impl.client.exec; package org.apache.http.impl.client.builder;
import java.io.IOException; import java.io.IOException;
import java.lang.reflect.UndeclaredThrowableException; import java.lang.reflect.UndeclaredThrowableException;
@ -42,7 +42,7 @@ import org.apache.http.protocol.HttpContext;
* @since 4.3 * @since 4.3
*/ */
@ThreadSafe @ThreadSafe
public class BackoffStrategyExec implements ClientExecChain { class BackoffStrategyExec implements ClientExecChain {
private final ClientExecChain requestExecutor; private final ClientExecChain requestExecutor;
private final ConnectionBackoffStrategy connectionBackoffStrategy; private final ConnectionBackoffStrategy connectionBackoffStrategy;

View File

@ -25,7 +25,7 @@
* *
*/ */
package org.apache.http.impl.client.exec; package org.apache.http.impl.client.builder;
import java.io.IOException; import java.io.IOException;
@ -47,7 +47,7 @@ import org.apache.http.protocol.HttpContext;
* *
* @since 4.3 * @since 4.3
*/ */
public interface ClientExecChain { interface ClientExecChain {
HttpResponseWrapper execute( HttpResponseWrapper execute(
HttpRoute route, HttpRoute route,

View File

@ -25,7 +25,7 @@
* *
*/ */
package org.apache.http.impl.client.exec; package org.apache.http.impl.client.builder;
import java.io.IOException; import java.io.IOException;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;

View File

@ -25,7 +25,7 @@
* *
*/ */
package org.apache.http.impl.client; package org.apache.http.impl.client.builder;
import java.net.ProxySelector; import java.net.ProxySelector;
import java.util.ArrayList; import java.util.ArrayList;
@ -76,13 +76,16 @@ import org.apache.http.impl.auth.DigestSchemeFactory;
import org.apache.http.impl.auth.KerberosSchemeFactory; import org.apache.http.impl.auth.KerberosSchemeFactory;
import org.apache.http.impl.auth.NTLMSchemeFactory; import org.apache.http.impl.auth.NTLMSchemeFactory;
import org.apache.http.impl.auth.SPNegoSchemeFactory; import org.apache.http.impl.auth.SPNegoSchemeFactory;
import org.apache.http.impl.client.exec.BackoffStrategyExec; import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.exec.ClientExecChain; import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.exec.MainClientExec; import org.apache.http.impl.client.DefaultConnectionKeepAliveStrategy;
import org.apache.http.impl.client.exec.ProtocolExec; import org.apache.http.impl.client.DefaultHttpRequestRetryHandler;
import org.apache.http.impl.client.exec.RedirectExec; import org.apache.http.impl.client.DefaultRedirectStrategy;
import org.apache.http.impl.client.exec.RetryExec; import org.apache.http.impl.client.DefaultUserTokenHandler;
import org.apache.http.impl.client.exec.ServiceUnavailableRetryExec; import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.NoopUserTokenHandler;
import org.apache.http.impl.client.ProxyAuthenticationStrategy;
import org.apache.http.impl.client.TargetAuthenticationStrategy;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.impl.conn.DefaultHttpRoutePlanner; import org.apache.http.impl.conn.DefaultHttpRoutePlanner;
import org.apache.http.impl.conn.ProxySelectorRoutePlanner; import org.apache.http.impl.conn.ProxySelectorRoutePlanner;
@ -226,7 +229,11 @@ public class HttpClientBuilder {
private int maxConnTotal = 0; private int maxConnTotal = 0;
private int maxConnPerRoute = 0; private int maxConnPerRoute = 0;
public HttpClientBuilder() { public static HttpClientBuilder create() {
return new HttpClientBuilder();
}
HttpClientBuilder() {
super(); super();
} }
@ -432,7 +439,7 @@ public class HttpClientBuilder {
return protocolExec; return protocolExec;
} }
public HttpClient build() { public CloseableHttpClient build() {
// Create main request executor // Create main request executor
HttpRequestExecutor requestExec = this.requestExec; HttpRequestExecutor requestExec = this.requestExec;
if (requestExec == null) { if (requestExec == null) {

View File

@ -25,7 +25,7 @@
* *
*/ */
package org.apache.http.impl.client.exec; package org.apache.http.impl.client.builder;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
@ -57,7 +57,7 @@ import org.apache.http.protocol.HTTP;
* @since 4.3 * @since 4.3
*/ */
@NotThreadSafe @NotThreadSafe
public class HttpRequestWrapper extends AbstractHttpMessage implements HttpRequest { class HttpRequestWrapper extends AbstractHttpMessage implements HttpRequest {
private final HttpRequest original; private final HttpRequest original;

View File

@ -25,9 +25,8 @@
* *
*/ */
package org.apache.http.impl.client.exec; package org.apache.http.impl.client.builder;
import java.io.Closeable;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import java.io.OutputStream; import java.io.OutputStream;
@ -41,6 +40,7 @@ import org.apache.http.HttpResponse;
import org.apache.http.ProtocolVersion; import org.apache.http.ProtocolVersion;
import org.apache.http.StatusLine; import org.apache.http.StatusLine;
import org.apache.http.annotation.NotThreadSafe; import org.apache.http.annotation.NotThreadSafe;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.conn.ConnectionReleaseTrigger; import org.apache.http.conn.ConnectionReleaseTrigger;
import org.apache.http.conn.EofSensorInputStream; import org.apache.http.conn.EofSensorInputStream;
import org.apache.http.conn.EofSensorWatcher; import org.apache.http.conn.EofSensorWatcher;
@ -55,7 +55,7 @@ import org.apache.http.util.EntityUtils;
* @since 4.3 * @since 4.3
*/ */
@NotThreadSafe @NotThreadSafe
public class HttpResponseWrapper implements HttpResponse, ConnectionReleaseTrigger, Closeable { class HttpResponseWrapper implements CloseableHttpResponse, ConnectionReleaseTrigger {
private final HttpResponse original; private final HttpResponse original;
private final ConnectionReleaseTriggerImpl connReleaseTrigger; private final ConnectionReleaseTriggerImpl connReleaseTrigger;

View File

@ -25,7 +25,7 @@
* *
*/ */
package org.apache.http.impl.client; package org.apache.http.impl.client.builder;
import java.io.IOException; import java.io.IOException;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
@ -33,13 +33,13 @@ import java.util.concurrent.TimeUnit;
import org.apache.http.HttpException; import org.apache.http.HttpException;
import org.apache.http.HttpHost; import org.apache.http.HttpHost;
import org.apache.http.HttpRequest; import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
import org.apache.http.annotation.ThreadSafe; import org.apache.http.annotation.ThreadSafe;
import org.apache.http.auth.AuthSchemeRegistry; import org.apache.http.auth.AuthSchemeRegistry;
import org.apache.http.auth.AuthState; import org.apache.http.auth.AuthState;
import org.apache.http.client.ClientProtocolException; import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.CookieStore; import org.apache.http.client.CookieStore;
import org.apache.http.client.CredentialsProvider; import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpExecutionAware; import org.apache.http.client.methods.HttpExecutionAware;
import org.apache.http.client.params.ClientPNames; import org.apache.http.client.params.ClientPNames;
import org.apache.http.client.protocol.ClientContext; import org.apache.http.client.protocol.ClientContext;
@ -51,8 +51,7 @@ import org.apache.http.conn.routing.HttpRoute;
import org.apache.http.conn.routing.HttpRoutePlanner; import org.apache.http.conn.routing.HttpRoutePlanner;
import org.apache.http.conn.scheme.SchemeRegistry; import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.cookie.CookieSpecRegistry; import org.apache.http.cookie.CookieSpecRegistry;
import org.apache.http.impl.client.exec.ClientExecChain; import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.exec.HttpRequestWrapper;
import org.apache.http.params.DefaultedHttpParams; import org.apache.http.params.DefaultedHttpParams;
import org.apache.http.params.HttpParams; import org.apache.http.params.HttpParams;
import org.apache.http.params.SyncBasicHttpParams; import org.apache.http.params.SyncBasicHttpParams;
@ -62,8 +61,9 @@ import org.apache.http.protocol.HttpContext;
/** /**
* @since 4.3 * @since 4.3
*/ */
@SuppressWarnings("deprecation")
@ThreadSafe @ThreadSafe
class InternalHttpClient extends AbstractBasicHttpClient { class InternalHttpClient extends CloseableHttpClient {
private final ClientExecChain execChain; private final ClientExecChain execChain;
private final HttpClientConnectionManager connManager; private final HttpClientConnectionManager connManager;
@ -143,7 +143,7 @@ class InternalHttpClient extends AbstractBasicHttpClient {
return context; return context;
} }
public HttpResponse execute( public CloseableHttpResponse execute(
final HttpHost target, final HttpHost target,
final HttpRequest request, final HttpRequest request,
final HttpContext context) throws IOException, ClientProtocolException { final HttpContext context) throws IOException, ClientProtocolException {
@ -173,6 +173,10 @@ class InternalHttpClient extends AbstractBasicHttpClient {
return this.params; return this.params;
} }
public void close() {
getConnectionManager().shutdown();
}
public ClientConnectionManager getConnectionManager() { public ClientConnectionManager getConnectionManager() {
return new ClientConnectionManager() { return new ClientConnectionManager() {

View File

@ -25,7 +25,7 @@
* *
*/ */
package org.apache.http.impl.client.exec; package org.apache.http.impl.client.builder;
import java.io.IOException; import java.io.IOException;
import java.io.InterruptedIOException; import java.io.InterruptedIOException;
@ -107,7 +107,7 @@ import org.apache.http.util.EntityUtils;
* @since 4.3 * @since 4.3
*/ */
@ThreadSafe @ThreadSafe
public class MainClientExec implements ClientExecChain { class MainClientExec implements ClientExecChain {
private final Log log = LogFactory.getLog(getClass()); private final Log log = LogFactory.getLog(getClass());

View File

@ -25,7 +25,7 @@
* *
*/ */
package org.apache.http.impl.client.exec; package org.apache.http.impl.client.builder;
import java.io.IOException; import java.io.IOException;
import java.net.URI; import java.net.URI;
@ -52,7 +52,7 @@ import org.apache.http.protocol.HttpProcessor;
* @since 4.3 * @since 4.3
*/ */
@ThreadSafe @ThreadSafe
public class ProtocolExec implements ClientExecChain { class ProtocolExec implements ClientExecChain {
private final Log log = LogFactory.getLog(getClass()); private final Log log = LogFactory.getLog(getClass());

View File

@ -25,7 +25,7 @@
* *
*/ */
package org.apache.http.impl.client.exec; package org.apache.http.impl.client.builder;
import java.io.IOException; import java.io.IOException;
import java.net.URI; import java.net.URI;
@ -62,7 +62,7 @@ import org.apache.http.protocol.HttpContext;
* @since 4.3 * @since 4.3
*/ */
@ThreadSafe @ThreadSafe
public class RedirectExec implements ClientExecChain { class RedirectExec implements ClientExecChain {
private final Log log = LogFactory.getLog(getClass()); private final Log log = LogFactory.getLog(getClass());

View File

@ -25,7 +25,7 @@
* *
*/ */
package org.apache.http.impl.client.exec; package org.apache.http.impl.client.builder;
import java.io.IOException; import java.io.IOException;
@ -46,7 +46,7 @@ import org.apache.http.protocol.HttpContext;
* @since 4.3 * @since 4.3
*/ */
@NotThreadSafe // e.g. managedConn @NotThreadSafe // e.g. managedConn
public class RetryExec implements ClientExecChain { class RetryExec implements ClientExecChain {
private final Log log = LogFactory.getLog(getClass()); private final Log log = LogFactory.getLog(getClass());

View File

@ -25,7 +25,7 @@
* *
*/ */
package org.apache.http.impl.client.exec; package org.apache.http.impl.client.builder;
import java.io.IOException; import java.io.IOException;
import java.io.InterruptedIOException; import java.io.InterruptedIOException;
@ -46,7 +46,7 @@ import org.apache.http.protocol.HttpContext;
* @since 4.3 * @since 4.3
*/ */
@ThreadSafe @ThreadSafe
public class ServiceUnavailableRetryExec implements ClientExecChain { class ServiceUnavailableRetryExec implements ClientExecChain {
private final Log log = LogFactory.getLog(getClass()); private final Log log = LogFactory.getLog(getClass());

View File

@ -72,6 +72,7 @@ import org.apache.http.conn.OperatedClientConnection;
* *
* @since 4.0 * @since 4.0
*/ */
@SuppressWarnings("deprecation")
@NotThreadSafe // connSecure, targetHost @NotThreadSafe // connSecure, targetHost
public class DefaultClientConnection extends SocketHttpClientConnection public class DefaultClientConnection extends SocketHttpClientConnection
implements OperatedClientConnection, HttpSSLConnection, HttpContext { implements OperatedClientConnection, HttpSSLConnection, HttpContext {

View File

@ -27,17 +27,10 @@
package org.apache.http.client.utils; package org.apache.http.client.utils;
import org.apache.http.HttpResponse; import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.junit.Test; import org.junit.Test;
public class TestHttpClientUtils { public class TestHttpClientUtils {
@Test
public void testCloseQuietlyNullClient() throws Exception {
HttpClient httpClient = null;
HttpClientUtils.closeQuietly(httpClient);
}
@Test @Test
public void testCloseQuietlyResponseNull() throws Exception { public void testCloseQuietlyResponseNull() throws Exception {
HttpResponse response = null; HttpResponse response = null;

View File

@ -38,7 +38,7 @@ import org.apache.http.HttpResponse;
import org.apache.http.HttpResponseInterceptor; import org.apache.http.HttpResponseInterceptor;
import org.apache.http.client.HttpClient; import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.localserver.LocalTestServer; import org.apache.http.localserver.LocalTestServer;
import org.apache.http.localserver.RandomHandler; import org.apache.http.localserver.RandomHandler;
@ -83,7 +83,7 @@ public class TestConnectionReuse {
mgr.setMaxTotal(5); mgr.setMaxTotal(5);
mgr.setDefaultMaxPerRoute(5); mgr.setDefaultMaxPerRoute(5);
HttpClient client = new HttpClientBuilder().setConnectionManager(mgr).build(); HttpClient client = HttpClients.custom().setConnectionManager(mgr).build();
HttpHost target = new HttpHost(saddress.getHostName(), saddress.getPort(), "http"); HttpHost target = new HttpHost(saddress.getHostName(), saddress.getPort(), "http");
WorkerThread[] workers = new WorkerThread[10]; WorkerThread[] workers = new WorkerThread[10];
@ -142,7 +142,7 @@ public class TestConnectionReuse {
mgr.setMaxTotal(5); mgr.setMaxTotal(5);
mgr.setDefaultMaxPerRoute(5); mgr.setDefaultMaxPerRoute(5);
HttpClient client = new HttpClientBuilder().setConnectionManager(mgr).build(); HttpClient client = HttpClients.custom().setConnectionManager(mgr).build();
HttpHost target = new HttpHost(saddress.getHostName(), saddress.getPort(), "http"); HttpHost target = new HttpHost(saddress.getHostName(), saddress.getPort(), "http");
@ -192,7 +192,7 @@ public class TestConnectionReuse {
mgr.setMaxTotal(5); mgr.setMaxTotal(5);
mgr.setDefaultMaxPerRoute(5); mgr.setDefaultMaxPerRoute(5);
HttpClient client = new HttpClientBuilder().setConnectionManager(mgr).build(); HttpClient client = HttpClients.custom().setConnectionManager(mgr).build();
HttpHost target = new HttpHost(saddress.getHostName(), saddress.getPort(), "http"); HttpHost target = new HttpHost(saddress.getHostName(), saddress.getPort(), "http");
@ -243,7 +243,7 @@ public class TestConnectionReuse {
mgr.setMaxTotal(1); mgr.setMaxTotal(1);
mgr.setDefaultMaxPerRoute(1); mgr.setDefaultMaxPerRoute(1);
HttpClient client = new HttpClientBuilder().setConnectionManager(mgr).build(); HttpClient client = HttpClients.custom().setConnectionManager(mgr).build();
HttpHost target = new HttpHost(saddress.getHostName(), saddress.getPort(), "http"); HttpHost target = new HttpHost(saddress.getHostName(), saddress.getPort(), "http");

View File

@ -57,7 +57,7 @@ public class TestRequestRetryHandler {
HttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(schemeRegistry); HttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(schemeRegistry);
TestHttpRequestRetryHandler testRetryHandler = new TestHttpRequestRetryHandler(); TestHttpRequestRetryHandler testRetryHandler = new TestHttpRequestRetryHandler();
HttpClient client = new HttpClientBuilder() HttpClient client = HttpClients.custom()
.setConnectionManager(connManager) .setConnectionManager(connManager)
.setRetryHandler(testRetryHandler).build(); .setRetryHandler(testRetryHandler).build();

View File

@ -25,18 +25,18 @@
*/ */
package org.apache.http.impl.client.integration; package org.apache.http.impl.client.integration;
import org.apache.http.client.HttpClient; import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.localserver.LocalServerTestBase; import org.apache.http.localserver.LocalServerTestBase;
import org.junit.After; import org.junit.After;
public class IntegrationTestBase extends LocalServerTestBase { public class IntegrationTestBase extends LocalServerTestBase {
protected HttpClient httpclient; protected CloseableHttpClient httpclient;
@After @After
public void shutDownClient() throws Exception { public void shutDownClient() throws Exception {
if (this.httpclient != null) { if (this.httpclient != null) {
this.httpclient.getConnectionManager().shutdown(); this.httpclient.close();
} }
} }

View File

@ -50,7 +50,8 @@ import org.apache.http.conn.routing.HttpRoute;
import org.apache.http.conn.scheme.Scheme; import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry; import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.entity.StringEntity; import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.impl.conn.SchemeRegistryFactory; import org.apache.http.impl.conn.SchemeRegistryFactory;
import org.apache.http.message.BasicHeader; import org.apache.http.message.BasicHeader;
@ -110,7 +111,7 @@ public class TestAbortHandling extends IntegrationTestBase {
t.start(); t.start();
this.httpclient = new HttpClientBuilder().build(); this.httpclient = HttpClients.createDefault();
HttpContext context = new BasicHttpContext(); HttpContext context = new BasicHttpContext();
try { try {
@ -123,11 +124,6 @@ public class TestAbortHandling extends IntegrationTestBase {
Assert.assertNotNull("Request should exist",reqWrapper); Assert.assertNotNull("Request should exist",reqWrapper);
} }
/**
* Tests that if abort is called on an {@link AbortableHttpRequest} while
* {@link DefaultRequestDirector} is allocating a connection, that the
* connection is properly aborted.
*/
@Test @Test
public void testAbortInAllocate() throws Exception { public void testAbortInAllocate() throws Exception {
CountDownLatch connLatch = new CountDownLatch(1); CountDownLatch connLatch = new CountDownLatch(1);
@ -135,7 +131,7 @@ public class TestAbortHandling extends IntegrationTestBase {
final ConMan conMan = new ConMan(connLatch, awaitLatch); final ConMan conMan = new ConMan(connLatch, awaitLatch);
final AtomicReference<Throwable> throwableRef = new AtomicReference<Throwable>(); final AtomicReference<Throwable> throwableRef = new AtomicReference<Throwable>();
final CountDownLatch getLatch = new CountDownLatch(1); final CountDownLatch getLatch = new CountDownLatch(1);
final HttpClient client = new HttpClientBuilder().setConnectionManager(conMan).build(); final CloseableHttpClient client = HttpClients.custom().setConnectionManager(conMan).build();
final HttpContext context = new BasicHttpContext(); final HttpContext context = new BasicHttpContext();
final HttpGet httpget = new HttpGet("http://www.example.com/a"); final HttpGet httpget = new HttpGet("http://www.example.com/a");
this.httpclient = client; this.httpclient = client;
@ -175,7 +171,7 @@ public class TestAbortHandling extends IntegrationTestBase {
final PoolingHttpClientConnectionManager conMan = new PoolingHttpClientConnectionManager(); final PoolingHttpClientConnectionManager conMan = new PoolingHttpClientConnectionManager();
final AtomicReference<Throwable> throwableRef = new AtomicReference<Throwable>(); final AtomicReference<Throwable> throwableRef = new AtomicReference<Throwable>();
final CountDownLatch getLatch = new CountDownLatch(1); final CountDownLatch getLatch = new CountDownLatch(1);
final HttpClient client = new HttpClientBuilder().setConnectionManager(conMan).build(); final CloseableHttpClient client = HttpClients.custom().setConnectionManager(conMan).build();
final HttpContext context = new BasicHttpContext(); final HttpContext context = new BasicHttpContext();
final HttpGet httpget = new CustomGet("a", releaseLatch); final HttpGet httpget = new CustomGet("a", releaseLatch);
this.httpclient = client; this.httpclient = client;
@ -215,7 +211,7 @@ public class TestAbortHandling extends IntegrationTestBase {
final AtomicReference<Throwable> throwableRef = new AtomicReference<Throwable>(); final AtomicReference<Throwable> throwableRef = new AtomicReference<Throwable>();
final CountDownLatch getLatch = new CountDownLatch(1); final CountDownLatch getLatch = new CountDownLatch(1);
final CountDownLatch startLatch = new CountDownLatch(1); final CountDownLatch startLatch = new CountDownLatch(1);
final HttpClient client = new HttpClientBuilder().setConnectionManager(conMan).build(); final CloseableHttpClient client = HttpClients.custom().setConnectionManager(conMan).build();
final HttpContext context = new BasicHttpContext(); final HttpContext context = new BasicHttpContext();
final HttpGet httpget = new HttpGet("a"); final HttpGet httpget = new HttpGet("a");
this.httpclient = client; this.httpclient = client;
@ -261,7 +257,7 @@ public class TestAbortHandling extends IntegrationTestBase {
final ConnMan4 conMan = new ConnMan4(connLatch, awaitLatch); final ConnMan4 conMan = new ConnMan4(connLatch, awaitLatch);
final AtomicReference<Throwable> throwableRef = new AtomicReference<Throwable>(); final AtomicReference<Throwable> throwableRef = new AtomicReference<Throwable>();
final CountDownLatch getLatch = new CountDownLatch(1); final CountDownLatch getLatch = new CountDownLatch(1);
final HttpClient client = new HttpClientBuilder().setConnectionManager(conMan).build(); final CloseableHttpClient client = HttpClients.custom().setConnectionManager(conMan).build();
final HttpContext context = new BasicHttpContext(); final HttpContext context = new BasicHttpContext();
final HttpGet httpget = new HttpGet("a"); final HttpGet httpget = new HttpGet("a");
this.httpclient = client; this.httpclient = client;
@ -315,7 +311,7 @@ public class TestAbortHandling extends IntegrationTestBase {
Mockito.any(HttpRoute.class), Mockito.any())).thenReturn(connrequest); Mockito.any(HttpRoute.class), Mockito.any())).thenReturn(connrequest);
Mockito.when(connmgr.getSchemeRegistry()).thenReturn(schemeRegistry); Mockito.when(connmgr.getSchemeRegistry()).thenReturn(schemeRegistry);
final HttpClient client = new HttpClientBuilder().setConnectionManager(connmgr).build(); final HttpClient client = HttpClients.custom().setConnectionManager(connmgr).build();
final HttpContext context = new BasicHttpContext(); final HttpContext context = new BasicHttpContext();
final HttpGet httpget = new HttpGet("http://www.example.com/a"); final HttpGet httpget = new HttpGet("http://www.example.com/a");

View File

@ -49,11 +49,11 @@ import org.apache.http.client.methods.HttpPut;
import org.apache.http.client.protocol.ClientContext; import org.apache.http.client.protocol.ClientContext;
import org.apache.http.entity.InputStreamEntity; import org.apache.http.entity.InputStreamEntity;
import org.apache.http.entity.StringEntity; import org.apache.http.entity.StringEntity;
import org.apache.http.impl.auth.BasicScheme;
import org.apache.http.impl.client.BasicAuthCache; import org.apache.http.impl.client.BasicAuthCache;
import org.apache.http.impl.client.BasicCredentialsProvider; import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.client.TargetAuthenticationStrategy; import org.apache.http.impl.client.TargetAuthenticationStrategy;
import org.apache.http.impl.auth.BasicScheme;
import org.apache.http.localserver.BasicAuthTokenExtractor; import org.apache.http.localserver.BasicAuthTokenExtractor;
import org.apache.http.localserver.LocalTestServer; import org.apache.http.localserver.LocalTestServer;
import org.apache.http.localserver.RequestBasicAuth; import org.apache.http.localserver.RequestBasicAuth;
@ -164,7 +164,7 @@ public class TestClientAuthentication extends IntegrationTestBase {
this.localServer.register("*", new AuthHandler()); this.localServer.register("*", new AuthHandler());
TestCredentialsProvider credsProvider = new TestCredentialsProvider(null); TestCredentialsProvider credsProvider = new TestCredentialsProvider(null);
this.httpclient = new HttpClientBuilder().setCredentialsProvider(credsProvider).build(); this.httpclient = HttpClients.custom().setCredentialsProvider(credsProvider).build();
HttpGet httpget = new HttpGet("/"); HttpGet httpget = new HttpGet("/");
@ -185,7 +185,7 @@ public class TestClientAuthentication extends IntegrationTestBase {
TestCredentialsProvider credsProvider = new TestCredentialsProvider( TestCredentialsProvider credsProvider = new TestCredentialsProvider(
new UsernamePasswordCredentials("test", "all-wrong")); new UsernamePasswordCredentials("test", "all-wrong"));
this.httpclient = new HttpClientBuilder().setCredentialsProvider(credsProvider).build(); this.httpclient = HttpClients.custom().setCredentialsProvider(credsProvider).build();
HttpGet httpget = new HttpGet("/"); HttpGet httpget = new HttpGet("/");
@ -206,7 +206,7 @@ public class TestClientAuthentication extends IntegrationTestBase {
TestCredentialsProvider credsProvider = new TestCredentialsProvider( TestCredentialsProvider credsProvider = new TestCredentialsProvider(
new UsernamePasswordCredentials("test", "test")); new UsernamePasswordCredentials("test", "test"));
this.httpclient = new HttpClientBuilder().setCredentialsProvider(credsProvider).build(); this.httpclient = HttpClients.custom().setCredentialsProvider(credsProvider).build();
HttpGet httpget = new HttpGet("/"); HttpGet httpget = new HttpGet("/");
@ -237,7 +237,7 @@ public class TestClientAuthentication extends IntegrationTestBase {
TestCredentialsProvider credsProvider = new TestCredentialsProvider( TestCredentialsProvider credsProvider = new TestCredentialsProvider(
new UsernamePasswordCredentials("test", "test")); new UsernamePasswordCredentials("test", "test"));
this.httpclient = new HttpClientBuilder().setCredentialsProvider(credsProvider).build(); this.httpclient = HttpClients.custom().setCredentialsProvider(credsProvider).build();
HttpPut httpput = new HttpPut("/"); HttpPut httpput = new HttpPut("/");
httpput.setEntity(new InputStreamEntity( httpput.setEntity(new InputStreamEntity(
@ -259,7 +259,7 @@ public class TestClientAuthentication extends IntegrationTestBase {
TestCredentialsProvider credsProvider = new TestCredentialsProvider( TestCredentialsProvider credsProvider = new TestCredentialsProvider(
new UsernamePasswordCredentials("test", "test")); new UsernamePasswordCredentials("test", "test"));
this.httpclient = new HttpClientBuilder().setCredentialsProvider(credsProvider).build(); this.httpclient = HttpClients.custom().setCredentialsProvider(credsProvider).build();
HttpPut httpput = new HttpPut("/"); HttpPut httpput = new HttpPut("/");
httpput.setEntity(new InputStreamEntity( httpput.setEntity(new InputStreamEntity(
@ -286,7 +286,7 @@ public class TestClientAuthentication extends IntegrationTestBase {
TestCredentialsProvider credsProvider = new TestCredentialsProvider( TestCredentialsProvider credsProvider = new TestCredentialsProvider(
new UsernamePasswordCredentials("test", "test")); new UsernamePasswordCredentials("test", "test"));
this.httpclient = new HttpClientBuilder().setCredentialsProvider(credsProvider).build(); this.httpclient = HttpClients.custom().setCredentialsProvider(credsProvider).build();
HttpPost httppost = new HttpPost("/"); HttpPost httppost = new HttpPost("/");
httppost.setEntity(new StringEntity("some important stuff", Consts.ASCII)); httppost.setEntity(new StringEntity("some important stuff", Consts.ASCII));
@ -308,7 +308,7 @@ public class TestClientAuthentication extends IntegrationTestBase {
TestCredentialsProvider credsProvider = new TestCredentialsProvider( TestCredentialsProvider credsProvider = new TestCredentialsProvider(
new UsernamePasswordCredentials("test", "test")); new UsernamePasswordCredentials("test", "test"));
this.httpclient = new HttpClientBuilder().setCredentialsProvider(credsProvider).build(); this.httpclient = HttpClients.custom().setCredentialsProvider(credsProvider).build();
HttpPost httppost = new HttpPost("/"); HttpPost httppost = new HttpPost("/");
httppost.setEntity(new InputStreamEntity( httppost.setEntity(new InputStreamEntity(
@ -361,7 +361,7 @@ public class TestClientAuthentication extends IntegrationTestBase {
new UsernamePasswordCredentials("test", "test")); new UsernamePasswordCredentials("test", "test"));
TestTargetAuthenticationStrategy authStrategy = new TestTargetAuthenticationStrategy(); TestTargetAuthenticationStrategy authStrategy = new TestTargetAuthenticationStrategy();
this.httpclient = new HttpClientBuilder() this.httpclient = HttpClients.custom()
.setCredentialsProvider(credsProvider) .setCredentialsProvider(credsProvider)
.setTargetAuthenticationStrategy(authStrategy) .setTargetAuthenticationStrategy(authStrategy)
.build(); .build();
@ -393,7 +393,7 @@ public class TestClientAuthentication extends IntegrationTestBase {
HttpHost target = getServerHttp(); HttpHost target = getServerHttp();
HttpGet httpget = new HttpGet("http://test:test@" + target.toHostString() + "/"); HttpGet httpget = new HttpGet("http://test:test@" + target.toHostString() + "/");
this.httpclient = new HttpClientBuilder().build(); this.httpclient = HttpClients.custom().build();
HttpResponse response = this.httpclient.execute(getServerHttp(), httpget); HttpResponse response = this.httpclient.execute(getServerHttp(), httpget);
HttpEntity entity = response.getEntity(); HttpEntity entity = response.getEntity();
@ -409,7 +409,7 @@ public class TestClientAuthentication extends IntegrationTestBase {
HttpHost target = getServerHttp(); HttpHost target = getServerHttp();
HttpGet httpget = new HttpGet("http://test:all-wrong@" + target.toHostString() + "/"); HttpGet httpget = new HttpGet("http://test:all-wrong@" + target.toHostString() + "/");
this.httpclient = new HttpClientBuilder().build(); this.httpclient = HttpClients.custom().build();
HttpResponse response = this.httpclient.execute(getServerHttp(), httpget); HttpResponse response = this.httpclient.execute(getServerHttp(), httpget);
HttpEntity entity = response.getEntity(); HttpEntity entity = response.getEntity();
@ -457,7 +457,7 @@ public class TestClientAuthentication extends IntegrationTestBase {
credsProvider.setCredentials(AuthScope.ANY, credsProvider.setCredentials(AuthScope.ANY,
new UsernamePasswordCredentials("test", "test")); new UsernamePasswordCredentials("test", "test"));
this.httpclient = new HttpClientBuilder() this.httpclient = HttpClients.custom()
.setCredentialsProvider(credsProvider) .setCredentialsProvider(credsProvider)
.build(); .build();
@ -488,7 +488,7 @@ public class TestClientAuthentication extends IntegrationTestBase {
credsProvider.setCredentials(AuthScope.ANY, credsProvider.setCredentials(AuthScope.ANY,
new UsernamePasswordCredentials("test", "stuff")); new UsernamePasswordCredentials("test", "stuff"));
this.httpclient = new HttpClientBuilder() this.httpclient = HttpClients.custom()
.setCredentialsProvider(credsProvider) .setCredentialsProvider(credsProvider)
.build(); .build();

View File

@ -41,7 +41,7 @@ import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider; import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpGet;
import org.apache.http.entity.StringEntity; import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.impl.client.HttpClients;
import org.apache.http.localserver.LocalTestServer; import org.apache.http.localserver.LocalTestServer;
import org.apache.http.localserver.RequestBasicAuth; import org.apache.http.localserver.RequestBasicAuth;
import org.apache.http.protocol.BasicHttpProcessor; import org.apache.http.protocol.BasicHttpProcessor;
@ -137,7 +137,7 @@ public class TestClientAuthenticationFallBack extends IntegrationTestBase {
TestCredentialsProvider credsProvider = new TestCredentialsProvider( TestCredentialsProvider credsProvider = new TestCredentialsProvider(
new UsernamePasswordCredentials("test", "test")); new UsernamePasswordCredentials("test", "test"));
this.httpclient = new HttpClientBuilder().setCredentialsProvider(credsProvider).build(); this.httpclient = HttpClients.custom().setCredentialsProvider(credsProvider).build();
HttpGet httpget = new HttpGet("/"); HttpGet httpget = new HttpGet("/");

View File

@ -47,7 +47,7 @@ import org.apache.http.client.methods.HttpGet;
import org.apache.http.entity.StringEntity; import org.apache.http.entity.StringEntity;
import org.apache.http.impl.auth.BasicScheme; import org.apache.http.impl.auth.BasicScheme;
import org.apache.http.impl.auth.BasicSchemeFactory; import org.apache.http.impl.auth.BasicSchemeFactory;
import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.client.TargetAuthenticationStrategy; import org.apache.http.impl.client.TargetAuthenticationStrategy;
import org.apache.http.localserver.LocalTestServer; import org.apache.http.localserver.LocalTestServer;
import org.apache.http.localserver.RequestBasicAuth; import org.apache.http.localserver.RequestBasicAuth;
@ -177,7 +177,7 @@ public class TestClientReauthentication extends IntegrationTestBase {
TestCredentialsProvider credsProvider = new TestCredentialsProvider( TestCredentialsProvider credsProvider = new TestCredentialsProvider(
new UsernamePasswordCredentials("test", "test")); new UsernamePasswordCredentials("test", "test"));
this.httpclient = new HttpClientBuilder() this.httpclient = HttpClients.custom()
.registerAuthScheme("MyBasic", myBasicAuthSchemeFactory) .registerAuthScheme("MyBasic", myBasicAuthSchemeFactory)
.setTargetAuthenticationStrategy(myAuthStrategy) .setTargetAuthenticationStrategy(myAuthStrategy)
.setCredentialsProvider(credsProvider) .setCredentialsProvider(credsProvider)

View File

@ -44,7 +44,7 @@ import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.params.ClientPNames; import org.apache.http.client.params.ClientPNames;
import org.apache.http.entity.InputStreamEntity; import org.apache.http.entity.InputStreamEntity;
import org.apache.http.entity.StringEntity; import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.impl.client.HttpClients;
import org.apache.http.protocol.BasicHttpContext; import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.ExecutionContext; import org.apache.http.protocol.ExecutionContext;
import org.apache.http.protocol.HttpContext; import org.apache.http.protocol.HttpContext;
@ -88,7 +88,7 @@ public class TestClientRequestExecution extends IntegrationTestBase {
HttpHost target = new HttpHost("localhost", port); HttpHost target = new HttpHost("localhost", port);
this.httpclient = new HttpClientBuilder().build(); this.httpclient = HttpClients.custom().build();
this.httpclient.getParams().setParameter(ClientPNames.DEFAULT_HOST, target); this.httpclient.getParams().setParameter(ClientPNames.DEFAULT_HOST, target);
String s = "/path"; String s = "/path";
@ -110,7 +110,7 @@ public class TestClientRequestExecution extends IntegrationTestBase {
String s = "http://localhost:" + port; String s = "http://localhost:" + port;
HttpGet httpget = new HttpGet(s); HttpGet httpget = new HttpGet(s);
this.httpclient = new HttpClientBuilder().build(); this.httpclient = HttpClients.custom().build();
HttpResponse response = this.httpclient.execute(getServerHttp(), httpget, context); HttpResponse response = this.httpclient.execute(getServerHttp(), httpget, context);
EntityUtils.consume(response.getEntity()); EntityUtils.consume(response.getEntity());
@ -136,7 +136,7 @@ public class TestClientRequestExecution extends IntegrationTestBase {
String s = "http://localhost:" + port; String s = "http://localhost:" + port;
HttpGet httpget = new HttpGet(s); HttpGet httpget = new HttpGet(s);
this.httpclient = new HttpClientBuilder().build(); this.httpclient = HttpClients.custom().build();
String virtHost = "virtual"; String virtHost = "virtual";
httpget.getParams().setParameter(ClientPNames.VIRTUAL_HOST, new HttpHost(virtHost, port)); httpget.getParams().setParameter(ClientPNames.VIRTUAL_HOST, new HttpHost(virtHost, port));
HttpResponse response = this.httpclient.execute(getServerHttp(), httpget, context); HttpResponse response = this.httpclient.execute(getServerHttp(), httpget, context);
@ -166,7 +166,7 @@ public class TestClientRequestExecution extends IntegrationTestBase {
String s = "http://localhost:" + port; String s = "http://localhost:" + port;
HttpGet httpget = new HttpGet(s); HttpGet httpget = new HttpGet(s);
this.httpclient = new HttpClientBuilder().build(); this.httpclient = HttpClients.custom().build();
String virtHost = "virtual"; String virtHost = "virtual";
int virtPort = 9876; int virtPort = 9876;
httpget.getParams().setParameter(ClientPNames.VIRTUAL_HOST, new HttpHost(virtHost, virtPort)); httpget.getParams().setParameter(ClientPNames.VIRTUAL_HOST, new HttpHost(virtHost, virtPort));
@ -194,7 +194,7 @@ public class TestClientRequestExecution extends IntegrationTestBase {
String s = "http://localhost:" + port; String s = "http://localhost:" + port;
HttpGet httpget = new HttpGet(s); HttpGet httpget = new HttpGet(s);
this.httpclient = new HttpClientBuilder().build(); this.httpclient = HttpClients.custom().build();
String virtHost = "virtual"; String virtHost = "virtual";
this.httpclient.getParams().setParameter(ClientPNames.VIRTUAL_HOST, new HttpHost(virtHost, port)); this.httpclient.getParams().setParameter(ClientPNames.VIRTUAL_HOST, new HttpHost(virtHost, port));
HttpResponse response = this.httpclient.execute(getServerHttp(), httpget, context); HttpResponse response = this.httpclient.execute(getServerHttp(), httpget, context);
@ -219,7 +219,7 @@ public class TestClientRequestExecution extends IntegrationTestBase {
HttpHost target1 = new HttpHost("whatever", 80); HttpHost target1 = new HttpHost("whatever", 80);
HttpHost target2 = new HttpHost("localhost", port); HttpHost target2 = new HttpHost("localhost", port);
this.httpclient = new HttpClientBuilder().build(); this.httpclient = HttpClients.custom().build();
this.httpclient.getParams().setParameter(ClientPNames.DEFAULT_HOST, target1); this.httpclient.getParams().setParameter(ClientPNames.DEFAULT_HOST, target1);
String s = "/path"; String s = "/path";
@ -284,7 +284,7 @@ public class TestClientRequestExecution extends IntegrationTestBase {
}; };
this.httpclient = new HttpClientBuilder() this.httpclient = HttpClients.custom()
.addInterceptorFirst(interceptor) .addInterceptorFirst(interceptor)
.setRequestExecutor(new FaultyHttpRequestExecutor("Oppsie")) .setRequestExecutor(new FaultyHttpRequestExecutor("Oppsie"))
.setRetryHandler(requestRetryHandler) .setRetryHandler(requestRetryHandler)
@ -324,7 +324,7 @@ public class TestClientRequestExecution extends IntegrationTestBase {
}; };
this.httpclient = new HttpClientBuilder() this.httpclient = HttpClients.custom()
.setRequestExecutor(new FaultyHttpRequestExecutor("a message showing that this failed")) .setRequestExecutor(new FaultyHttpRequestExecutor("a message showing that this failed"))
.setRetryHandler(requestRetryHandler) .setRetryHandler(requestRetryHandler)
.build(); .build();

View File

@ -40,12 +40,12 @@ import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse; import org.apache.http.HttpResponse;
import org.apache.http.MalformedChunkCodingException; import org.apache.http.MalformedChunkCodingException;
import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.ConnectionRequest;
import org.apache.http.conn.ConnectionPoolTimeoutException; import org.apache.http.conn.ConnectionPoolTimeoutException;
import org.apache.http.conn.ConnectionRequest;
import org.apache.http.conn.routing.HttpRoute; import org.apache.http.conn.routing.HttpRoute;
import org.apache.http.entity.BasicHttpEntity; import org.apache.http.entity.BasicHttpEntity;
import org.apache.http.impl.DefaultHttpServerConnection; import org.apache.http.impl.DefaultHttpServerConnection;
import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.pool.PoolStats; import org.apache.http.pool.PoolStats;
import org.apache.http.protocol.ExecutionContext; import org.apache.http.protocol.ExecutionContext;
@ -64,7 +64,7 @@ public class TestConnectionAutoRelease extends IntegrationTestBase {
public void setUp() throws Exception { public void setUp() throws Exception {
startServer(); startServer();
this.mgr = new PoolingHttpClientConnectionManager(); this.mgr = new PoolingHttpClientConnectionManager();
this.httpclient = new HttpClientBuilder().setConnectionManager(this.mgr).build(); this.httpclient = HttpClients.custom().setConnectionManager(this.mgr).build();
} }
@Test @Test

View File

@ -52,7 +52,7 @@ import org.apache.http.client.methods.HttpGet;
import org.apache.http.entity.InputStreamEntity; import org.apache.http.entity.InputStreamEntity;
import org.apache.http.entity.StringEntity; import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.BasicResponseHandler; import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.protocol.HttpContext; import org.apache.http.protocol.HttpContext;
import org.apache.http.protocol.HttpRequestHandler; import org.apache.http.protocol.HttpRequestHandler;
@ -95,7 +95,7 @@ public class TestContentCodings extends IntegrationTestBase {
} }
}); });
this.httpclient = new HttpClientBuilder().build(); this.httpclient = HttpClients.custom().build();
HttpGet request = new HttpGet("/some-resource"); HttpGet request = new HttpGet("/some-resource");
HttpResponse response = this.httpclient.execute(getServerHttp(), request); HttpResponse response = this.httpclient.execute(getServerHttp(), request);
Assert.assertEquals(HttpStatus.SC_NO_CONTENT, response.getStatusLine().getStatusCode()); Assert.assertEquals(HttpStatus.SC_NO_CONTENT, response.getStatusLine().getStatusCode());
@ -115,7 +115,7 @@ public class TestContentCodings extends IntegrationTestBase {
this.localServer.register("*", createDeflateEncodingRequestHandler(entityText, false)); this.localServer.register("*", createDeflateEncodingRequestHandler(entityText, false));
this.httpclient = new HttpClientBuilder().build(); this.httpclient = HttpClients.custom().build();
HttpGet request = new HttpGet("/some-resource"); HttpGet request = new HttpGet("/some-resource");
HttpResponse response = this.httpclient.execute(getServerHttp(), request); HttpResponse response = this.httpclient.execute(getServerHttp(), request);
@ -136,7 +136,7 @@ public class TestContentCodings extends IntegrationTestBase {
this.localServer.register("*", createDeflateEncodingRequestHandler(entityText, true)); this.localServer.register("*", createDeflateEncodingRequestHandler(entityText, true));
this.httpclient = new HttpClientBuilder().build(); this.httpclient = HttpClients.custom().build();
HttpGet request = new HttpGet("/some-resource"); HttpGet request = new HttpGet("/some-resource");
HttpResponse response = this.httpclient.execute(getServerHttp(), request); HttpResponse response = this.httpclient.execute(getServerHttp(), request);
@ -155,7 +155,7 @@ public class TestContentCodings extends IntegrationTestBase {
this.localServer.register("*", createGzipEncodingRequestHandler(entityText)); this.localServer.register("*", createGzipEncodingRequestHandler(entityText));
this.httpclient = new HttpClientBuilder().build(); this.httpclient = HttpClients.custom().build();
HttpGet request = new HttpGet("/some-resource"); HttpGet request = new HttpGet("/some-resource");
HttpResponse response = this.httpclient.execute(getServerHttp(), request); HttpResponse response = this.httpclient.execute(getServerHttp(), request);
@ -184,7 +184,7 @@ public class TestContentCodings extends IntegrationTestBase {
PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(); PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
cm.setMaxTotal(clients); cm.setMaxTotal(clients);
this.httpclient = new HttpClientBuilder().setConnectionManager(cm).build(); this.httpclient = HttpClients.custom().setConnectionManager(cm).build();
ExecutorService executor = Executors.newFixedThreadPool(clients); ExecutorService executor = Executors.newFixedThreadPool(clients);
@ -228,7 +228,7 @@ public class TestContentCodings extends IntegrationTestBase {
this.localServer.register("*", createGzipEncodingRequestHandler(entityText)); this.localServer.register("*", createGzipEncodingRequestHandler(entityText));
this.httpclient = new HttpClientBuilder().build(); this.httpclient = HttpClients.custom().build();
HttpGet request = new HttpGet("/some-resource"); HttpGet request = new HttpGet("/some-resource");
HttpResponse response = this.httpclient.execute(getServerHttp(), request); HttpResponse response = this.httpclient.execute(getServerHttp(), request);
@ -251,7 +251,7 @@ public class TestContentCodings extends IntegrationTestBase {
this.localServer.register("*", createDeflateEncodingRequestHandler(entityText, true)); this.localServer.register("*", createDeflateEncodingRequestHandler(entityText, true));
this.httpclient = new HttpClientBuilder().build(); this.httpclient = HttpClients.custom().build();
HttpGet request = new HttpGet("/some-resource"); HttpGet request = new HttpGet("/some-resource");
HttpResponse response = this.httpclient.execute(getServerHttp(), request); HttpResponse response = this.httpclient.execute(getServerHttp(), request);
@ -268,7 +268,7 @@ public class TestContentCodings extends IntegrationTestBase {
this.localServer.register("*", createGzipEncodingRequestHandler(entityText)); this.localServer.register("*", createGzipEncodingRequestHandler(entityText));
this.httpclient = new HttpClientBuilder().build(); this.httpclient = HttpClients.custom().build();
HttpGet request = new HttpGet("/some-resource"); HttpGet request = new HttpGet("/some-resource");
String response = this.httpclient.execute(getServerHttp(), request, new BasicResponseHandler()); String response = this.httpclient.execute(getServerHttp(), request, new BasicResponseHandler());
@ -281,7 +281,7 @@ public class TestContentCodings extends IntegrationTestBase {
this.localServer.register("*", createDeflateEncodingRequestHandler(entityText, false)); this.localServer.register("*", createDeflateEncodingRequestHandler(entityText, false));
this.httpclient = new HttpClientBuilder().build(); this.httpclient = HttpClients.custom().build();
HttpGet request = new HttpGet("/some-resource"); HttpGet request = new HttpGet("/some-resource");
String response = this.httpclient.execute(getServerHttp(), request, new BasicResponseHandler()); String response = this.httpclient.execute(getServerHttp(), request, new BasicResponseHandler());

View File

@ -45,7 +45,7 @@ import org.apache.http.cookie.SM;
import org.apache.http.cookie.SetCookie2; import org.apache.http.cookie.SetCookie2;
import org.apache.http.entity.StringEntity; import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.BasicCookieStore; import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicHeader; import org.apache.http.message.BasicHeader;
import org.apache.http.protocol.BasicHttpContext; import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.ExecutionContext; import org.apache.http.protocol.ExecutionContext;
@ -64,7 +64,7 @@ public class TestCookie2Support extends IntegrationTestBase {
@Before @Before
public void setUp() throws Exception { public void setUp() throws Exception {
startServer(); startServer();
this.httpclient = new HttpClientBuilder().build(); this.httpclient = HttpClients.custom().build();
} }
private static class CookieVer0Service implements HttpRequestHandler { private static class CookieVer0Service implements HttpRequestHandler {

View File

@ -37,7 +37,7 @@ import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpUriRequest; import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.conn.HttpClientConnectionManager; import org.apache.http.conn.HttpClientConnectionManager;
import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.localserver.LocalServerTestBase; import org.apache.http.localserver.LocalServerTestBase;
import org.apache.http.localserver.LocalTestServer; import org.apache.http.localserver.LocalTestServer;
@ -60,7 +60,7 @@ public class TestIdleConnectionEviction extends LocalServerTestBase {
cm.setDefaultMaxPerRoute(10); cm.setDefaultMaxPerRoute(10);
cm.setMaxTotal(50); cm.setMaxTotal(50);
HttpClient httpclient = new HttpClientBuilder().setConnectionManager(cm).build(); HttpClient httpclient = HttpClients.custom().setConnectionManager(cm).build();
IdleConnectionMonitor idleConnectionMonitor = new IdleConnectionMonitor(cm); IdleConnectionMonitor idleConnectionMonitor = new IdleConnectionMonitor(cm);
idleConnectionMonitor.start(); idleConnectionMonitor.start();

View File

@ -50,7 +50,7 @@ import org.apache.http.client.protocol.ClientContext;
import org.apache.http.cookie.SM; import org.apache.http.cookie.SM;
import org.apache.http.entity.StringEntity; import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.BasicCookieStore; import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.cookie.BasicClientCookie; import org.apache.http.impl.cookie.BasicClientCookie;
import org.apache.http.message.BasicHeader; import org.apache.http.message.BasicHeader;
import org.apache.http.protocol.BasicHttpContext; import org.apache.http.protocol.BasicHttpContext;
@ -71,7 +71,7 @@ public class TestRedirects extends IntegrationTestBase {
@Before @Before
public void setUp() throws Exception { public void setUp() throws Exception {
startServer(); startServer();
this.httpclient = new HttpClientBuilder().build(); this.httpclient = HttpClients.createDefault();
} }
private static class BasicRedirectService implements HttpRequestHandler { private static class BasicRedirectService implements HttpRequestHandler {

View File

@ -45,13 +45,12 @@ import org.apache.http.entity.StringEntity;
import org.apache.http.impl.auth.SPNegoScheme; import org.apache.http.impl.auth.SPNegoScheme;
import org.apache.http.impl.auth.SPNegoSchemeFactory; import org.apache.http.impl.auth.SPNegoSchemeFactory;
import org.apache.http.impl.client.BasicCredentialsProvider; import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicHeader; import org.apache.http.message.BasicHeader;
import org.apache.http.params.HttpParams; import org.apache.http.params.HttpParams;
import org.apache.http.protocol.HttpContext; import org.apache.http.protocol.HttpContext;
import org.apache.http.protocol.HttpRequestHandler; import org.apache.http.protocol.HttpRequestHandler;
import org.apache.http.util.EntityUtils; import org.apache.http.util.EntityUtils;
import org.ietf.jgss.GSSContext; import org.ietf.jgss.GSSContext;
import org.ietf.jgss.GSSCredential; import org.ietf.jgss.GSSCredential;
import org.ietf.jgss.GSSManager; import org.ietf.jgss.GSSManager;
@ -64,7 +63,7 @@ import org.mockito.Matchers;
import org.mockito.Mockito; import org.mockito.Mockito;
/** /**
* Tests for {@link NegotiateScheme}. * Tests for {@link SPNegoScheme}.
*/ */
public class TestSPNegoScheme extends IntegrationTestBase { public class TestSPNegoScheme extends IntegrationTestBase {
@ -164,7 +163,7 @@ public class TestSPNegoScheme extends IntegrationTestBase {
Credentials use_jaas_creds = new UseJaasCredentials(); Credentials use_jaas_creds = new UseJaasCredentials();
credentialsProvider.setCredentials(new AuthScope(null, -1, null), use_jaas_creds); credentialsProvider.setCredentials(new AuthScope(null, -1, null), use_jaas_creds);
this.httpclient = new HttpClientBuilder() this.httpclient = HttpClients.custom()
.registerAuthScheme(AuthPolicy.SPNEGO, nsf) .registerAuthScheme(AuthPolicy.SPNEGO, nsf)
.setCredentialsProvider(credentialsProvider) .setCredentialsProvider(credentialsProvider)
.build(); .build();
@ -196,7 +195,7 @@ public class TestSPNegoScheme extends IntegrationTestBase {
Credentials use_jaas_creds = new UseJaasCredentials(); Credentials use_jaas_creds = new UseJaasCredentials();
credentialsProvider.setCredentials(new AuthScope(null, -1, null), use_jaas_creds); credentialsProvider.setCredentials(new AuthScope(null, -1, null), use_jaas_creds);
this.httpclient = new HttpClientBuilder() this.httpclient = HttpClients.custom()
.registerAuthScheme(AuthPolicy.SPNEGO, nsf) .registerAuthScheme(AuthPolicy.SPNEGO, nsf)
.setCredentialsProvider(credentialsProvider) .setCredentialsProvider(credentialsProvider)
.build(); .build();

View File

@ -37,7 +37,7 @@ import org.apache.http.client.HttpClient;
import org.apache.http.client.UserTokenHandler; import org.apache.http.client.UserTokenHandler;
import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpGet;
import org.apache.http.entity.StringEntity; import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.params.BasicHttpParams; import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams; import org.apache.http.params.HttpConnectionParams;
@ -104,7 +104,7 @@ public class TestStatefulConnManagement extends IntegrationTestBase {
}; };
this.httpclient = new HttpClientBuilder() this.httpclient = HttpClients.custom()
.setConnectionManager(mgr) .setConnectionManager(mgr)
.setUserTokenHandler(userTokenHandler) .setUserTokenHandler(userTokenHandler)
.build(); .build();
@ -235,7 +235,7 @@ public class TestStatefulConnManagement extends IntegrationTestBase {
}; };
this.httpclient = new HttpClientBuilder() this.httpclient = HttpClients.custom()
.setConnectionManager(connMngr) .setConnectionManager(connMngr)
.setUserTokenHandler(userTokenHandler) .setUserTokenHandler(userTokenHandler)
.build(); .build();