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.client.BasicAuthCache;
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.protocol.BasicHttpContext;
@ -93,7 +93,7 @@ public class Executor {
CONNMGR = new PoolingHttpClientConnectionManager(schemeRegistry);
CONNMGR.setDefaultMaxPerRoute(100);
CONNMGR.setMaxTotal(200);
CLIENT = new HttpClientBuilder().setConnectionManager(CONNMGR).build();
CLIENT = HttpClientBuilder.create().setConnectionManager(CONNMGR).build();
}
public static Executor newInstance() {

View File

@ -28,10 +28,10 @@
package org.apache.http.examples.client;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.CloseableHttpResponse;
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.
@ -39,12 +39,13 @@ import org.apache.http.impl.client.DefaultHttpClient;
public class ClientAbortMethod {
public final static void main(String[] args) throws Exception {
HttpClient httpclient = new DefaultHttpClient();
CloseableHttpClient httpclient = HttpClients.createDefault();
try {
HttpGet httpget = new HttpGet("http://www.apache.org/");
System.out.println("executing request " + httpget.getURI());
HttpResponse response = httpclient.execute(httpget);
CloseableHttpResponse response = httpclient.execute(httpget);
try {
HttpEntity entity = response.getEntity();
System.out.println("----------------------------------------");
@ -58,10 +59,10 @@ public class ClientAbortMethod {
// Call abort on the request object
httpget.abort();
} finally {
// When HttpClient instance is no longer needed,
// shut down the connection manager to ensure
// immediate deallocation of all system resources
httpclient.getConnectionManager().shutdown();
response.close();
}
} finally {
httpclient.close();
}
}

View File

@ -26,11 +26,14 @@
package org.apache.http.examples.client;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.auth.AuthScope;
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.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;
/**
@ -40,16 +43,18 @@ import org.apache.http.util.EntityUtils;
public class ClientAuthentication {
public static void main(String[] args) throws Exception {
DefaultHttpClient httpclient = new DefaultHttpClient();
try {
httpclient.getCredentialsProvider().setCredentials(
CredentialsProvider credsProvider = new BasicCredentialsProvider();
credsProvider.setCredentials(
new AuthScope("localhost", 443),
new UsernamePasswordCredentials("username", "password"));
CloseableHttpClient httpclient = HttpClients.custom()
.setCredentialsProvider(credsProvider).build();
try {
HttpGet httpget = new HttpGet("https://localhost/protected");
System.out.println("executing request" + httpget.getRequestLine());
HttpResponse response = httpclient.execute(httpget);
CloseableHttpResponse response = httpclient.execute(httpget);
try {
HttpEntity entity = response.getEntity();
System.out.println("----------------------------------------");
@ -59,10 +64,10 @@ public class ClientAuthentication {
}
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();
response.close();
}
} finally {
httpclient.close();
}
}
}

View File

@ -30,11 +30,11 @@ import java.io.File;
import java.io.FileInputStream;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
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;
/**
@ -47,7 +47,7 @@ public class ClientChunkEncodedPost {
System.out.println("File path not given");
System.exit(1);
}
HttpClient httpclient = new DefaultHttpClient();
CloseableHttpClient httpclient = HttpClients.createDefault();
try {
HttpPost httppost = new HttpPost("http://localhost:8080" +
"/servlets-examples/servlet/RequestInfoExample");
@ -67,7 +67,8 @@ public class ClientChunkEncodedPost {
httppost.setEntity(reqEntity);
System.out.println("executing request " + httppost.getRequestLine());
HttpResponse response = httpclient.execute(httppost);
CloseableHttpResponse response = httpclient.execute(httppost);
try {
HttpEntity resEntity = response.getEntity();
System.out.println("----------------------------------------");
@ -78,10 +79,10 @@ public class ClientChunkEncodedPost {
}
EntityUtils.consume(resEntity);
} finally {
// When HttpClient instance is no longer needed,
// shut down the connection manager to ensure
// immediate deallocation of all system resources
httpclient.getConnectionManager().shutdown();
response.close();
}
} finally {
httpclient.close();
}
}

View File

@ -31,10 +31,10 @@ import java.io.IOException;
import java.io.InputStream;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.CloseableHttpResponse;
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
@ -43,14 +43,14 @@ import org.apache.http.impl.client.DefaultHttpClient;
public class ClientConnectionRelease {
public final static void main(String[] args) throws Exception {
HttpClient httpclient = new DefaultHttpClient();
CloseableHttpClient httpclient = HttpClients.createDefault();
try {
HttpGet httpget = new HttpGet("http://www.apache.org/");
// Execute HTTP request
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("----------------------------------------");
@ -69,23 +69,16 @@ public class ClientConnectionRelease {
// In case of an IOException the connection will be released
// back to the connection manager automatically
throw ex;
} 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) {}
instream.close();
}
}
} finally {
// When HttpClient instance is no longer needed,
// shut down the connection manager to ensure
// immediate deallocation of all system resources
httpclient.getConnectionManager().shutdown();
response.close();
}
} finally {
httpclient.close();
}
}

View File

@ -30,19 +30,18 @@ package org.apache.http.examples.client;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
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.protocol.ClientContext;
import org.apache.http.cookie.Cookie;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.HttpContext;
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.HttpContext;
import org.apache.http.util.EntityUtils;
/**
* This example demonstrates the use of a local HTTP context populated with
* custom attributes.
@ -50,8 +49,7 @@ import org.apache.http.util.EntityUtils;
public class ClientCustomContext {
public final static void main(String[] args) throws Exception {
HttpClient httpclient = new DefaultHttpClient();
CloseableHttpClient httpclient = HttpClients.createDefault();
try {
// Create a local instance of cookie store
CookieStore cookieStore = new BasicCookieStore();
@ -66,7 +64,8 @@ public class ClientCustomContext {
System.out.println("executing request " + httpget.getURI());
// Pass local context as a parameter
HttpResponse response = httpclient.execute(httpget, localContext);
CloseableHttpResponse response = httpclient.execute(httpget, localContext);
try {
HttpEntity entity = response.getEntity();
System.out.println("----------------------------------------");
@ -83,12 +82,11 @@ public class ClientCustomContext {
EntityUtils.consume(entity);
System.out.println("----------------------------------------");
} finally {
// When HttpClient instance is no longer needed,
// shut down the connection manager to ensure
// immediate deallocation of all system resources
httpclient.getConnectionManager().shutdown();
response.close();
}
} finally {
httpclient.close();
}
}

View File

@ -31,11 +31,11 @@ import java.io.FileInputStream;
import java.security.KeyStore;
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.conn.scheme.Scheme;
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;
/**
@ -45,25 +45,23 @@ import org.apache.http.util.EntityUtils;
public class ClientCustomSSL {
public final static void main(String[] args) throws Exception {
DefaultHttpClient httpclient = new DefaultHttpClient();
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) {}
instream.close();
}
SSLSocketFactory socketFactory = new SSLSocketFactory(trustStore);
Scheme sch = new Scheme("https", 443, socketFactory);
httpclient.getConnectionManager().getSchemeRegistry().register(sch);
CloseableHttpClient httpclient = HttpClients.custom()
.setSSLSocketFactory(new SSLSocketFactory(trustStore)).build();
try {
HttpGet httpget = new HttpGet("https://localhost/");
System.out.println("executing request" + httpget.getRequestLine());
HttpResponse response = httpclient.execute(httpget);
CloseableHttpResponse response = httpclient.execute(httpget);
try {
HttpEntity entity = response.getEntity();
System.out.println("----------------------------------------");
@ -72,12 +70,11 @@ public class ClientCustomSSL {
System.out.println("Response content length: " + entity.getContentLength());
}
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();
response.close();
}
} finally {
httpclient.close();
}
}

View File

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

View File

@ -30,10 +30,11 @@ package org.apache.http.examples.client;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.CloseableHttpResponse;
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;
/**
@ -44,19 +45,20 @@ import org.apache.http.util.EntityUtils;
public class ClientExecuteDirect {
public static void main(String[] args) throws Exception {
DefaultHttpClient httpclient = new DefaultHttpClient();
CloseableHttpClient httpclient = HttpClients.createDefault();
try {
HttpHost target = new HttpHost("www.apache.org", 80, "http");
HttpGet req = new HttpGet("/");
HttpGet request = new HttpGet("/");
System.out.println("executing request to " + target);
HttpResponse rsp = httpclient.execute(target, req);
HttpEntity entity = rsp.getEntity();
CloseableHttpResponse response = httpclient.execute(target, request);
try {
HttpEntity entity = response.getEntity();
System.out.println("----------------------------------------");
System.out.println(rsp.getStatusLine());
Header[] headers = rsp.getAllHeaders();
System.out.println(response.getStatusLine());
Header[] headers = response.getAllHeaders();
for (int i = 0; i < headers.length; i++) {
System.out.println(headers[i]);
}
@ -65,12 +67,11 @@ public class ClientExecuteDirect {
if (entity != null) {
System.out.println(EntityUtils.toString(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();
response.close();
}
} finally {
httpclient.close();
}
}

View File

@ -30,11 +30,12 @@ package org.apache.http.examples.client;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
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;
/**
@ -46,21 +47,21 @@ public class ClientExecuteProxy {
public static void main(String[] args)throws Exception {
HttpHost proxy = new HttpHost("127.0.0.1", 8080, "http");
DefaultHttpClient httpclient = new DefaultHttpClient();
CloseableHttpClient httpclient = HttpClients.createDefault();
try {
httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
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);
HttpResponse rsp = httpclient.execute(target, req);
HttpEntity entity = rsp.getEntity();
CloseableHttpResponse response = httpclient.execute(target, request);
try {
HttpEntity entity = response.getEntity();
System.out.println("----------------------------------------");
System.out.println(rsp.getStatusLine());
Header[] headers = rsp.getAllHeaders();
System.out.println(response.getStatusLine());
Header[] headers = response.getAllHeaders();
for (int i = 0; i<headers.length; i++) {
System.out.println(headers[i]);
}
@ -69,12 +70,11 @@ public class ClientExecuteProxy {
if (entity != null) {
System.out.println(EntityUtils.toString(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();
response.close();
}
} finally {
httpclient.close();
}
}

View File

@ -37,13 +37,17 @@ import java.net.UnknownHostException;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.ConnectTimeoutException;
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.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.HttpParams;
import org.apache.http.util.EntityUtils;
@ -56,23 +60,25 @@ import org.apache.http.util.EntityUtils;
public class ClientExecuteSOCKS {
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 {
httpclient.getParams().setParameter("socks.host", "mysockshost");
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");
HttpGet req = new HttpGet("/");
HttpGet request = new HttpGet("/");
System.out.println("executing request to " + target + " via SOCKS proxy");
HttpResponse rsp = httpclient.execute(target, req);
HttpEntity entity = rsp.getEntity();
CloseableHttpResponse response = httpclient.execute(target, request);
try {
HttpEntity entity = response.getEntity();
System.out.println("----------------------------------------");
System.out.println(rsp.getStatusLine());
Header[] headers = rsp.getAllHeaders();
System.out.println(response.getStatusLine());
Header[] headers = response.getAllHeaders();
for (int i = 0; i<headers.length; i++) {
System.out.println(headers[i]);
}
@ -81,12 +87,11 @@ public class ClientExecuteSOCKS {
if (entity != null) {
System.out.println(EntityUtils.toString(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();
response.close();
}
} finally {
httpclient.close();
}
}

View File

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

View File

@ -38,8 +38,10 @@ import org.apache.http.HttpRequestInterceptor;
import org.apache.http.HttpResponse;
import org.apache.http.HttpResponseInterceptor;
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.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.util.EntityUtils;
@ -59,9 +61,8 @@ import org.apache.http.util.EntityUtils;
public class ClientGZipContentCompression {
public final static void main(String[] args) throws Exception {
DefaultHttpClient httpclient = new DefaultHttpClient();
try {
httpclient.addRequestInterceptor(new HttpRequestInterceptor() {
CloseableHttpClient httpclient = HttpClients.custom()
.addInterceptorFirst(new HttpRequestInterceptor() {
public void process(
final HttpRequest request,
@ -69,11 +70,8 @@ public class ClientGZipContentCompression {
if (!request.containsHeader("Accept-Encoding")) {
request.addHeader("Accept-Encoding", "gzip");
}
}
});
httpclient.addResponseInterceptor(new HttpResponseInterceptor() {
}}).addInterceptorFirst(new HttpResponseInterceptor() {
public void process(
final HttpResponse response,
@ -94,14 +92,14 @@ public class ClientGZipContentCompression {
}
}
});
}).build();
try {
HttpGet httpget = new HttpGet("http://www.apache.org/");
// Execute HTTP request
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(response.getLastHeader("Content-Encoding"));
@ -116,12 +114,11 @@ public class ClientGZipContentCompression {
System.out.println("----------------------------------------");
System.out.println("Uncompressed size: "+content.length());
}
} finally {
// When HttpClient instance is no longer needed,
// shut down the connection manager to ensure
// immediate deallocation of all system resources
httpclient.getConnectionManager().shutdown();
response.close();
}
} finally {
httpclient.close();
}
}

View File

@ -30,16 +30,18 @@ import java.io.InputStreamReader;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.auth.AuthScheme;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.AuthState;
import org.apache.http.auth.Credentials;
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.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.ExecutionContext;
import org.apache.http.protocol.HttpContext;
@ -52,7 +54,9 @@ import org.apache.http.util.EntityUtils;
public class ClientInteractiveAuthentication {
public static void main(String[] args) throws Exception {
DefaultHttpClient httpclient = new DefaultHttpClient();
BasicCredentialsProvider credsProvider = new BasicCredentialsProvider();
CloseableHttpClient httpclient = HttpClients.custom()
.setCredentialsProvider(credsProvider).build();
try {
// Create local execution context
HttpContext localContext = new BasicHttpContext();
@ -62,8 +66,8 @@ public class ClientInteractiveAuthentication {
boolean trying = true;
while (trying) {
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());
@ -101,7 +105,7 @@ public class ClientInteractiveAuthentication {
if (user != null && user.length() > 0) {
Credentials creds = new UsernamePasswordCredentials(user, password);
httpclient.getCredentialsProvider().setCredentials(new AuthScope(authhost), creds);
credsProvider.setCredentials(new AuthScope(authhost), creds);
trying = true;
} else {
trying = false;
@ -109,13 +113,12 @@ public class ClientInteractiveAuthentication {
} else {
trying = false;
}
}
} finally {
// When HttpClient instance is no longer needed,
// shut down the connection manager to ensure
// immediate deallocation of all system resources
httpclient.getConnectionManager().shutdown();
response.close();
}
}
} finally {
httpclient.close();
}
}
}

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;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.PoolingClientConnectionManager;
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.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;
import org.apache.http.util.EntityUtils;
@ -46,10 +46,10 @@ public class ClientMultiThreadedExecution {
// Create an HttpClient with the ThreadSafeClientConnManager.
// This connection manager must be used if more than one thread will
// be using the HttpClient.
PoolingClientConnectionManager cm = new PoolingClientConnectionManager();
PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
cm.setMaxTotal(100);
HttpClient httpclient = new DefaultHttpClient(cm);
CloseableHttpClient httpclient = HttpClients.custom().setConnectionManager(cm).build();
try {
// create an array of URIs to perform GETs on
String[] urisToGet = {
@ -77,10 +77,7 @@ public class ClientMultiThreadedExecution {
}
} finally {
// When HttpClient instance is no longer needed,
// shut down the connection manager to ensure
// immediate deallocation of all system resources
httpclient.getConnectionManager().shutdown();
httpclient.close();
}
}
@ -89,12 +86,12 @@ public class ClientMultiThreadedExecution {
*/
static class GetThread extends Thread {
private final HttpClient httpClient;
private final CloseableHttpClient httpClient;
private final HttpContext context;
private final HttpGet httpget;
private final int id;
public GetThread(HttpClient httpClient, HttpGet httpget, int id) {
public GetThread(CloseableHttpClient httpClient, HttpGet httpget, int id) {
this.httpClient = httpClient;
this.context = new BasicHttpContext();
this.httpget = httpget;
@ -106,14 +103,10 @@ public class ClientMultiThreadedExecution {
*/
@Override
public void run() {
System.out.println(id + " - about to get something from " + httpget.getURI());
try {
// execute the method
HttpResponse response = httpClient.execute(httpget, context);
System.out.println(id + " - about to get something from " + httpget.getURI());
CloseableHttpResponse response = httpClient.execute(httpget, context);
try {
System.out.println(id + " - get executed");
// get the response body as an array of bytes
HttpEntity entity = response.getEntity();
@ -121,9 +114,10 @@ public class ClientMultiThreadedExecution {
byte[] bytes = EntityUtils.toByteArray(entity);
System.out.println(id + " - " + bytes.length + " bytes read");
}
} finally {
response.close();
}
} catch (Exception e) {
httpget.abort();
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.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
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.protocol.ClientContext;
import org.apache.http.impl.auth.BasicScheme;
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.util.EntityUtils;
@ -50,14 +53,14 @@ import org.apache.http.util.EntityUtils;
public class ClientPreemptiveBasicAuthentication {
public static void main(String[] args) throws Exception {
HttpHost targetHost = new HttpHost("localhost", 80, "http");
DefaultHttpClient httpclient = new DefaultHttpClient();
try {
httpclient.getCredentialsProvider().setCredentials(
CredentialsProvider credsProvider = new BasicCredentialsProvider();
credsProvider.setCredentials(
new AuthScope(targetHost.getHostName(), targetHost.getPort()),
new UsernamePasswordCredentials("username", "password"));
CloseableHttpClient httpclient = HttpClients.custom()
.setCredentialsProvider(credsProvider).build();
try {
// Create AuthCache instance
AuthCache authCache = new BasicAuthCache();
@ -76,7 +79,8 @@ public class ClientPreemptiveBasicAuthentication {
System.out.println("to target: " + targetHost);
for (int i = 0; i < 3; i++) {
HttpResponse response = httpclient.execute(targetHost, httpget, localcontext);
CloseableHttpResponse response = httpclient.execute(targetHost, httpget, localcontext);
try {
HttpEntity entity = response.getEntity();
System.out.println("----------------------------------------");
@ -85,13 +89,12 @@ public class ClientPreemptiveBasicAuthentication {
System.out.println("Response content length: " + entity.getContentLength());
}
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();
response.close();
}
}
} finally {
httpclient.close();
}
}

View File

@ -27,22 +27,25 @@ package org.apache.http.examples.client;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
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.protocol.ClientContext;
import org.apache.http.impl.auth.DigestScheme;
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.util.EntityUtils;
/**
* An example of HttpClient can be customized to authenticate
* preemptively using DIGEST scheme.
* <b/>
* <p/>
* Generally, preemptive authentication can be considered less
* secure than a response to an authentication challenge
* and therefore discouraged.
@ -50,14 +53,14 @@ import org.apache.http.util.EntityUtils;
public class ClientPreemptiveDigestAuthentication {
public static void main(String[] args) throws Exception {
HttpHost targetHost = new HttpHost("localhost", 80, "http");
DefaultHttpClient httpclient = new DefaultHttpClient();
try {
httpclient.getCredentialsProvider().setCredentials(
CredentialsProvider credsProvider = new BasicCredentialsProvider();
credsProvider.setCredentials(
new AuthScope(targetHost.getHostName(), targetHost.getPort()),
new UsernamePasswordCredentials("username", "password"));
CloseableHttpClient httpclient = HttpClients.custom()
.setCredentialsProvider(credsProvider).build();
try {
// Create AuthCache instance
AuthCache authCache = new BasicAuthCache();
@ -80,7 +83,8 @@ public class ClientPreemptiveDigestAuthentication {
System.out.println("to target: " + targetHost);
for (int i = 0; i < 3; i++) {
HttpResponse response = httpclient.execute(targetHost, httpget, localcontext);
CloseableHttpResponse response = httpclient.execute(targetHost, httpget, localcontext);
try {
HttpEntity entity = response.getEntity();
System.out.println("----------------------------------------");
@ -89,13 +93,12 @@ public class ClientPreemptiveDigestAuthentication {
System.out.println("Response content length: " + entity.getContentLength());
}
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();
response.close();
}
}
} finally {
httpclient.close();
}
}

View File

@ -27,12 +27,15 @@ package org.apache.http.examples.client;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.auth.AuthScope;
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.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;
/**
@ -42,13 +45,13 @@ import org.apache.http.util.EntityUtils;
public class ClientProxyAuthentication {
public static void main(String[] args) throws Exception {
DefaultHttpClient httpclient = new DefaultHttpClient();
try {
httpclient.getCredentialsProvider().setCredentials(
CredentialsProvider credsProvider = new BasicCredentialsProvider();
credsProvider.setCredentials(
new AuthScope("localhost", 8080),
new UsernamePasswordCredentials("username", "password"));
CloseableHttpClient httpclient = HttpClients.custom()
.setCredentialsProvider(credsProvider).build();
try {
HttpHost targetHost = new HttpHost("www.verisign.com", 443, "https");
HttpHost proxy = new HttpHost("localhost", 8080);
@ -60,7 +63,8 @@ public class ClientProxyAuthentication {
System.out.println("via proxy: " + proxy);
System.out.println("to target: " + targetHost);
HttpResponse response = httpclient.execute(targetHost, httpget);
CloseableHttpResponse response = httpclient.execute(targetHost, httpget);
try {
HttpEntity entity = response.getEntity();
System.out.println("----------------------------------------");
@ -69,12 +73,11 @@ public class ClientProxyAuthentication {
System.out.println("Response content length: " + entity.getContentLength());
}
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();
response.close();
}
} finally {
httpclient.close();
}
}
}

View File

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

View File

@ -30,28 +30,28 @@ import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
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.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.util.EntityUtils;
public class QuickStart {
public static void main(String[] args) throws Exception {
DefaultHttpClient httpclient = new DefaultHttpClient();
CloseableHttpClient httpclient = HttpClients.createDefault();
try {
HttpGet httpGet = new HttpGet("http://targethost/homepage");
HttpResponse response1 = httpclient.execute(httpGet);
CloseableHttpResponse 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().
// execution by calling CloseableHttpResponse#close().
try {
System.out.println(response1.getStatusLine());
@ -60,7 +60,7 @@ public class QuickStart {
// and ensure it is fully consumed
EntityUtils.consume(entity1);
} finally {
httpGet.releaseConnection();
response1.close();
}
HttpPost httpPost = new HttpPost("http://targethost/login");
@ -68,7 +68,7 @@ public class QuickStart {
nvps.add(new BasicNameValuePair("username", "vip"));
nvps.add(new BasicNameValuePair("password", "secret"));
httpPost.setEntity(new UrlEncodedFormEntity(nvps));
HttpResponse response2 = httpclient.execute(httpPost);
CloseableHttpResponse response2 = httpclient.execute(httpPost);
try {
System.out.println(response2.getStatusLine());
@ -77,7 +77,10 @@ public class QuickStart {
// and ensure it is fully consumed
EntityUtils.consume(entity2);
} finally {
httpPost.releaseConnection();
response2.close();
}
} finally {
httpclient.close();
}
}

View File

@ -34,6 +34,7 @@ import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.impl.client.builder.HttpClientBuilder;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.HttpContext;
@ -47,7 +48,7 @@ import org.apache.http.protocol.HttpContext;
* <p/>
* The usual execution flow can be demonstrated by the code snippet below:
* <PRE>
* HttpClient httpclient = new DefaultHttpClient();
* MinimalHttpClient httpclient = HttpClientBuilder.buildDefault();
*
* // Prepare a request object
* 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,
* // shut down the connection manager to ensure
* // immediate deallocation of all system resources
* httpclient.getConnectionManager().shutdown();
* // When HttpClient instance is no longer needed, it can be closed
* // to ensure immediate deallocation of all system resources
* httpclient.close();
* }
* </PRE>
*
* @since 4.0
*/
@SuppressWarnings("deprecation")
public interface HttpClient {
@ -119,7 +120,10 @@ public interface HttpClient {
* Obtains the connection manager used by this client.
*
* @return the connection manager
*
* @deprecated (4.3) use {@link HttpClientBuilder}.
*/
@Deprecated
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;
/**
* Static helpers for dealing with {@link HttpResponse}s and {@link HttpClient}s.
* Static helpers for dealing with {@link HttpResponse}s.
*
* @since 4.2
*/
@ -97,7 +97,10 @@ public class HttpClientUtils {
* @param httpClient
* the HttpClient to close, may be null or already closed.
* @since 4.2
*
* @deprecated (4.3) do not use.
*/
@Deprecated
public static void closeQuietly(final HttpClient httpClient) {
if (httpClient != null) {
httpClient.getConnectionManager().shutdown();

View File

@ -37,7 +37,6 @@ import org.apache.http.HttpException;
import org.apache.http.HttpHost;
import org.apache.http.HttpRequest;
import org.apache.http.HttpRequestInterceptor;
import org.apache.http.HttpResponse;
import org.apache.http.HttpResponseInterceptor;
import org.apache.http.annotation.GuardedBy;
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.RequestDirector;
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.ClientPNames;
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.NTLMSchemeFactory;
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.DefaultHttpRoutePlanner;
import org.apache.http.impl.conn.SchemeRegistryFactory;
@ -178,7 +179,7 @@ import org.apache.http.protocol.ImmutableHttpProcessor;
*/
@ThreadSafe
@Deprecated
public abstract class AbstractHttpClient extends AbstractBasicHttpClient {
public abstract class AbstractHttpClient extends CloseableHttpClient {
private final Log log = LogFactory.getLog(getClass());
@ -775,7 +776,7 @@ public abstract class AbstractHttpClient extends AbstractBasicHttpClient {
protocolProcessor = null;
}
public final HttpResponse execute(HttpHost target, HttpRequest request,
public final CloseableHttpResponse execute(HttpHost target, HttpRequest request,
HttpContext context)
throws IOException, ClientProtocolException {
@ -828,9 +829,10 @@ public abstract class AbstractHttpClient extends AbstractBasicHttpClient {
ClientPNames.DEFAULT_HOST);
HttpRoute route = routePlanner.determineRoute(targetForRoute, request, execContext);
HttpResponse out;
CloseableHttpResponse out;
try {
out = director.execute(target, request, execContext);
out = CloseableHttpResponseProxy.newProxy(
director.execute(target, request, execContext));
} catch (RuntimeException re) {
if (connectionBackoffStrategy.shouldBackoff(re)) {
backoffManager.backOff(route);
@ -851,7 +853,8 @@ public abstract class AbstractHttpClient extends AbstractBasicHttpClient {
}
return out;
} else {
return director.execute(target, request, execContext);
return CloseableHttpResponseProxy.newProxy(
director.execute(target, request, execContext));
}
} catch(HttpException httpException) {
throw new ClientProtocolException(httpException);
@ -976,4 +979,9 @@ public abstract class AbstractHttpClient extends AbstractBasicHttpClient {
(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.methods.HttpUriRequest;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.impl.client.builder.HttpClientBuilder;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.HttpContext;
import org.apache.http.util.EntityUtils;

View File

@ -27,6 +27,7 @@
package org.apache.http.impl.client;
import java.io.Closeable;
import java.io.IOException;
import java.lang.reflect.UndeclaredThrowableException;
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.HttpClient;
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.utils.URIUtils;
import org.apache.http.protocol.HttpContext;
import org.apache.http.util.EntityUtils;
/**
* Minimal implementation of {@link HttpClient} that also implements {@link Closeable}.
*
* @since 4.3
*/
@ThreadSafe
public abstract class AbstractBasicHttpClient implements HttpClient {
public abstract class CloseableHttpClient implements HttpClient, Closeable {
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 HttpContext context) throws IOException, ClientProtocolException {
if (request == null) {
@ -79,12 +86,12 @@ public abstract class AbstractBasicHttpClient implements HttpClient {
return target;
}
public HttpResponse execute(
public CloseableHttpResponse execute(
final HttpUriRequest request) throws IOException, ClientProtocolException {
return execute(request, (HttpContext) null);
}
public HttpResponse execute(
public CloseableHttpResponse execute(
final HttpHost target,
final HttpRequest request) throws IOException, ClientProtocolException {
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.ResponseContentEncoding;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.impl.client.builder.HttpClientBuilder;
import org.apache.http.params.HttpParams;
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.utils.URIUtils;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.impl.client.builder.HttpClientBuilder;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.BasicHttpContext;
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.ResponseProcessCookies;
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.CoreProtocolPNames;
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.entity.HttpEntityWrapper;
import org.apache.http.impl.client.exec.HttpRequestWrapper;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
@ -51,7 +50,7 @@ import org.apache.http.protocol.HTTP;
*
* @since 4.0
*
* @deprecated (4.3) use {@link HttpRequestWrapper}.
* @deprecated (4.3) do not use.
*/
@Deprecated
@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.RequestLine;
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.BasicRequestLine;
import org.apache.http.params.HttpProtocolParams;
@ -52,7 +51,7 @@ import org.apache.http.params.HttpProtocolParams;
*
* @since 4.0
*
* @deprecated (4.3) use {@link HttpRequestWrapper}.
* @deprecated (4.3) do not use.
*/
@NotThreadSafe
@Deprecated

View File

@ -35,6 +35,7 @@ import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.routing.HttpRoutePlanner;
import org.apache.http.impl.DefaultConnectionReuseStrategy;
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.ProxySelectorRoutePlanner;
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.lang.reflect.UndeclaredThrowableException;
@ -42,7 +42,7 @@ import org.apache.http.protocol.HttpContext;
* @since 4.3
*/
@ThreadSafe
public class BackoffStrategyExec implements ClientExecChain {
class BackoffStrategyExec implements ClientExecChain {
private final ClientExecChain requestExecutor;
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;
@ -47,7 +47,7 @@ import org.apache.http.protocol.HttpContext;
*
* @since 4.3
*/
public interface ClientExecChain {
interface ClientExecChain {
HttpResponseWrapper execute(
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.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.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.NTLMSchemeFactory;
import org.apache.http.impl.auth.SPNegoSchemeFactory;
import org.apache.http.impl.client.exec.BackoffStrategyExec;
import org.apache.http.impl.client.exec.ClientExecChain;
import org.apache.http.impl.client.exec.MainClientExec;
import org.apache.http.impl.client.exec.ProtocolExec;
import org.apache.http.impl.client.exec.RedirectExec;
import org.apache.http.impl.client.exec.RetryExec;
import org.apache.http.impl.client.exec.ServiceUnavailableRetryExec;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.DefaultConnectionKeepAliveStrategy;
import org.apache.http.impl.client.DefaultHttpRequestRetryHandler;
import org.apache.http.impl.client.DefaultRedirectStrategy;
import org.apache.http.impl.client.DefaultUserTokenHandler;
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.DefaultHttpRoutePlanner;
import org.apache.http.impl.conn.ProxySelectorRoutePlanner;
@ -226,7 +229,11 @@ public class HttpClientBuilder {
private int maxConnTotal = 0;
private int maxConnPerRoute = 0;
public HttpClientBuilder() {
public static HttpClientBuilder create() {
return new HttpClientBuilder();
}
HttpClientBuilder() {
super();
}
@ -432,7 +439,7 @@ public class HttpClientBuilder {
return protocolExec;
}
public HttpClient build() {
public CloseableHttpClient build() {
// Create main request executor
HttpRequestExecutor requestExec = this.requestExec;
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.InputStream;
@ -57,7 +57,7 @@ import org.apache.http.protocol.HTTP;
* @since 4.3
*/
@NotThreadSafe
public class HttpRequestWrapper extends AbstractHttpMessage implements HttpRequest {
class HttpRequestWrapper extends AbstractHttpMessage implements HttpRequest {
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.InputStream;
import java.io.OutputStream;
@ -41,6 +40,7 @@ import org.apache.http.HttpResponse;
import org.apache.http.ProtocolVersion;
import org.apache.http.StatusLine;
import org.apache.http.annotation.NotThreadSafe;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.conn.ConnectionReleaseTrigger;
import org.apache.http.conn.EofSensorInputStream;
import org.apache.http.conn.EofSensorWatcher;
@ -55,7 +55,7 @@ import org.apache.http.util.EntityUtils;
* @since 4.3
*/
@NotThreadSafe
public class HttpResponseWrapper implements HttpResponse, ConnectionReleaseTrigger, Closeable {
class HttpResponseWrapper implements CloseableHttpResponse, ConnectionReleaseTrigger {
private final HttpResponse original;
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.util.concurrent.TimeUnit;
@ -33,13 +33,13 @@ import java.util.concurrent.TimeUnit;
import org.apache.http.HttpException;
import org.apache.http.HttpHost;
import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
import org.apache.http.annotation.ThreadSafe;
import org.apache.http.auth.AuthSchemeRegistry;
import org.apache.http.auth.AuthState;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.CookieStore;
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.params.ClientPNames;
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.scheme.SchemeRegistry;
import org.apache.http.cookie.CookieSpecRegistry;
import org.apache.http.impl.client.exec.ClientExecChain;
import org.apache.http.impl.client.exec.HttpRequestWrapper;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.params.DefaultedHttpParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.SyncBasicHttpParams;
@ -62,8 +61,9 @@ import org.apache.http.protocol.HttpContext;
/**
* @since 4.3
*/
@SuppressWarnings("deprecation")
@ThreadSafe
class InternalHttpClient extends AbstractBasicHttpClient {
class InternalHttpClient extends CloseableHttpClient {
private final ClientExecChain execChain;
private final HttpClientConnectionManager connManager;
@ -143,7 +143,7 @@ class InternalHttpClient extends AbstractBasicHttpClient {
return context;
}
public HttpResponse execute(
public CloseableHttpResponse execute(
final HttpHost target,
final HttpRequest request,
final HttpContext context) throws IOException, ClientProtocolException {
@ -173,6 +173,10 @@ class InternalHttpClient extends AbstractBasicHttpClient {
return this.params;
}
public void close() {
getConnectionManager().shutdown();
}
public ClientConnectionManager getConnectionManager() {
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.InterruptedIOException;
@ -107,7 +107,7 @@ import org.apache.http.util.EntityUtils;
* @since 4.3
*/
@ThreadSafe
public class MainClientExec implements ClientExecChain {
class MainClientExec implements ClientExecChain {
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.net.URI;
@ -52,7 +52,7 @@ import org.apache.http.protocol.HttpProcessor;
* @since 4.3
*/
@ThreadSafe
public class ProtocolExec implements ClientExecChain {
class ProtocolExec implements ClientExecChain {
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.net.URI;
@ -62,7 +62,7 @@ import org.apache.http.protocol.HttpContext;
* @since 4.3
*/
@ThreadSafe
public class RedirectExec implements ClientExecChain {
class RedirectExec implements ClientExecChain {
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;
@ -46,7 +46,7 @@ import org.apache.http.protocol.HttpContext;
* @since 4.3
*/
@NotThreadSafe // e.g. managedConn
public class RetryExec implements ClientExecChain {
class RetryExec implements ClientExecChain {
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.InterruptedIOException;
@ -46,7 +46,7 @@ import org.apache.http.protocol.HttpContext;
* @since 4.3
*/
@ThreadSafe
public class ServiceUnavailableRetryExec implements ClientExecChain {
class ServiceUnavailableRetryExec implements ClientExecChain {
private final Log log = LogFactory.getLog(getClass());

View File

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

View File

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

View File

@ -38,7 +38,7 @@ import org.apache.http.HttpResponse;
import org.apache.http.HttpResponseInterceptor;
import org.apache.http.client.HttpClient;
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.localserver.LocalTestServer;
import org.apache.http.localserver.RandomHandler;
@ -83,7 +83,7 @@ public class TestConnectionReuse {
mgr.setMaxTotal(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");
WorkerThread[] workers = new WorkerThread[10];
@ -142,7 +142,7 @@ public class TestConnectionReuse {
mgr.setMaxTotal(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");
@ -192,7 +192,7 @@ public class TestConnectionReuse {
mgr.setMaxTotal(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");
@ -243,7 +243,7 @@ public class TestConnectionReuse {
mgr.setMaxTotal(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");

View File

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

View File

@ -25,18 +25,18 @@
*/
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.junit.After;
public class IntegrationTestBase extends LocalServerTestBase {
protected HttpClient httpclient;
protected CloseableHttpClient httpclient;
@After
public void shutDownClient() throws Exception {
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.SchemeRegistry;
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.SchemeRegistryFactory;
import org.apache.http.message.BasicHeader;
@ -110,7 +111,7 @@ public class TestAbortHandling extends IntegrationTestBase {
t.start();
this.httpclient = new HttpClientBuilder().build();
this.httpclient = HttpClients.createDefault();
HttpContext context = new BasicHttpContext();
try {
@ -123,11 +124,6 @@ public class TestAbortHandling extends IntegrationTestBase {
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
public void testAbortInAllocate() throws Exception {
CountDownLatch connLatch = new CountDownLatch(1);
@ -135,7 +131,7 @@ public class TestAbortHandling extends IntegrationTestBase {
final ConMan conMan = new ConMan(connLatch, awaitLatch);
final AtomicReference<Throwable> throwableRef = new AtomicReference<Throwable>();
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 HttpGet httpget = new HttpGet("http://www.example.com/a");
this.httpclient = client;
@ -175,7 +171,7 @@ public class TestAbortHandling extends IntegrationTestBase {
final PoolingHttpClientConnectionManager conMan = new PoolingHttpClientConnectionManager();
final AtomicReference<Throwable> throwableRef = new AtomicReference<Throwable>();
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 HttpGet httpget = new CustomGet("a", releaseLatch);
this.httpclient = client;
@ -215,7 +211,7 @@ public class TestAbortHandling extends IntegrationTestBase {
final AtomicReference<Throwable> throwableRef = new AtomicReference<Throwable>();
final CountDownLatch getLatch = 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 HttpGet httpget = new HttpGet("a");
this.httpclient = client;
@ -261,7 +257,7 @@ public class TestAbortHandling extends IntegrationTestBase {
final ConnMan4 conMan = new ConnMan4(connLatch, awaitLatch);
final AtomicReference<Throwable> throwableRef = new AtomicReference<Throwable>();
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 HttpGet httpget = new HttpGet("a");
this.httpclient = client;
@ -315,7 +311,7 @@ public class TestAbortHandling extends IntegrationTestBase {
Mockito.any(HttpRoute.class), Mockito.any())).thenReturn(connrequest);
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 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.entity.InputStreamEntity;
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.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.auth.BasicScheme;
import org.apache.http.localserver.BasicAuthTokenExtractor;
import org.apache.http.localserver.LocalTestServer;
import org.apache.http.localserver.RequestBasicAuth;
@ -164,7 +164,7 @@ public class TestClientAuthentication extends IntegrationTestBase {
this.localServer.register("*", new AuthHandler());
TestCredentialsProvider credsProvider = new TestCredentialsProvider(null);
this.httpclient = new HttpClientBuilder().setCredentialsProvider(credsProvider).build();
this.httpclient = HttpClients.custom().setCredentialsProvider(credsProvider).build();
HttpGet httpget = new HttpGet("/");
@ -185,7 +185,7 @@ public class TestClientAuthentication extends IntegrationTestBase {
TestCredentialsProvider credsProvider = new TestCredentialsProvider(
new UsernamePasswordCredentials("test", "all-wrong"));
this.httpclient = new HttpClientBuilder().setCredentialsProvider(credsProvider).build();
this.httpclient = HttpClients.custom().setCredentialsProvider(credsProvider).build();
HttpGet httpget = new HttpGet("/");
@ -206,7 +206,7 @@ public class TestClientAuthentication extends IntegrationTestBase {
TestCredentialsProvider credsProvider = new TestCredentialsProvider(
new UsernamePasswordCredentials("test", "test"));
this.httpclient = new HttpClientBuilder().setCredentialsProvider(credsProvider).build();
this.httpclient = HttpClients.custom().setCredentialsProvider(credsProvider).build();
HttpGet httpget = new HttpGet("/");
@ -237,7 +237,7 @@ public class TestClientAuthentication extends IntegrationTestBase {
TestCredentialsProvider credsProvider = new TestCredentialsProvider(
new UsernamePasswordCredentials("test", "test"));
this.httpclient = new HttpClientBuilder().setCredentialsProvider(credsProvider).build();
this.httpclient = HttpClients.custom().setCredentialsProvider(credsProvider).build();
HttpPut httpput = new HttpPut("/");
httpput.setEntity(new InputStreamEntity(
@ -259,7 +259,7 @@ public class TestClientAuthentication extends IntegrationTestBase {
TestCredentialsProvider credsProvider = new TestCredentialsProvider(
new UsernamePasswordCredentials("test", "test"));
this.httpclient = new HttpClientBuilder().setCredentialsProvider(credsProvider).build();
this.httpclient = HttpClients.custom().setCredentialsProvider(credsProvider).build();
HttpPut httpput = new HttpPut("/");
httpput.setEntity(new InputStreamEntity(
@ -286,7 +286,7 @@ public class TestClientAuthentication extends IntegrationTestBase {
TestCredentialsProvider credsProvider = new TestCredentialsProvider(
new UsernamePasswordCredentials("test", "test"));
this.httpclient = new HttpClientBuilder().setCredentialsProvider(credsProvider).build();
this.httpclient = HttpClients.custom().setCredentialsProvider(credsProvider).build();
HttpPost httppost = new HttpPost("/");
httppost.setEntity(new StringEntity("some important stuff", Consts.ASCII));
@ -308,7 +308,7 @@ public class TestClientAuthentication extends IntegrationTestBase {
TestCredentialsProvider credsProvider = new TestCredentialsProvider(
new UsernamePasswordCredentials("test", "test"));
this.httpclient = new HttpClientBuilder().setCredentialsProvider(credsProvider).build();
this.httpclient = HttpClients.custom().setCredentialsProvider(credsProvider).build();
HttpPost httppost = new HttpPost("/");
httppost.setEntity(new InputStreamEntity(
@ -361,7 +361,7 @@ public class TestClientAuthentication extends IntegrationTestBase {
new UsernamePasswordCredentials("test", "test"));
TestTargetAuthenticationStrategy authStrategy = new TestTargetAuthenticationStrategy();
this.httpclient = new HttpClientBuilder()
this.httpclient = HttpClients.custom()
.setCredentialsProvider(credsProvider)
.setTargetAuthenticationStrategy(authStrategy)
.build();
@ -393,7 +393,7 @@ public class TestClientAuthentication extends IntegrationTestBase {
HttpHost target = getServerHttp();
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);
HttpEntity entity = response.getEntity();
@ -409,7 +409,7 @@ public class TestClientAuthentication extends IntegrationTestBase {
HttpHost target = getServerHttp();
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);
HttpEntity entity = response.getEntity();
@ -457,7 +457,7 @@ public class TestClientAuthentication extends IntegrationTestBase {
credsProvider.setCredentials(AuthScope.ANY,
new UsernamePasswordCredentials("test", "test"));
this.httpclient = new HttpClientBuilder()
this.httpclient = HttpClients.custom()
.setCredentialsProvider(credsProvider)
.build();
@ -488,7 +488,7 @@ public class TestClientAuthentication extends IntegrationTestBase {
credsProvider.setCredentials(AuthScope.ANY,
new UsernamePasswordCredentials("test", "stuff"));
this.httpclient = new HttpClientBuilder()
this.httpclient = HttpClients.custom()
.setCredentialsProvider(credsProvider)
.build();

View File

@ -41,7 +41,7 @@ import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.methods.HttpGet;
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.RequestBasicAuth;
import org.apache.http.protocol.BasicHttpProcessor;
@ -137,7 +137,7 @@ public class TestClientAuthenticationFallBack extends IntegrationTestBase {
TestCredentialsProvider credsProvider = new TestCredentialsProvider(
new UsernamePasswordCredentials("test", "test"));
this.httpclient = new HttpClientBuilder().setCredentialsProvider(credsProvider).build();
this.httpclient = HttpClients.custom().setCredentialsProvider(credsProvider).build();
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.impl.auth.BasicScheme;
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.localserver.LocalTestServer;
import org.apache.http.localserver.RequestBasicAuth;
@ -177,7 +177,7 @@ public class TestClientReauthentication extends IntegrationTestBase {
TestCredentialsProvider credsProvider = new TestCredentialsProvider(
new UsernamePasswordCredentials("test", "test"));
this.httpclient = new HttpClientBuilder()
this.httpclient = HttpClients.custom()
.registerAuthScheme("MyBasic", myBasicAuthSchemeFactory)
.setTargetAuthenticationStrategy(myAuthStrategy)
.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.entity.InputStreamEntity;
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.ExecutionContext;
import org.apache.http.protocol.HttpContext;
@ -88,7 +88,7 @@ public class TestClientRequestExecution extends IntegrationTestBase {
HttpHost target = new HttpHost("localhost", port);
this.httpclient = new HttpClientBuilder().build();
this.httpclient = HttpClients.custom().build();
this.httpclient.getParams().setParameter(ClientPNames.DEFAULT_HOST, target);
String s = "/path";
@ -110,7 +110,7 @@ public class TestClientRequestExecution extends IntegrationTestBase {
String s = "http://localhost:" + port;
HttpGet httpget = new HttpGet(s);
this.httpclient = new HttpClientBuilder().build();
this.httpclient = HttpClients.custom().build();
HttpResponse response = this.httpclient.execute(getServerHttp(), httpget, context);
EntityUtils.consume(response.getEntity());
@ -136,7 +136,7 @@ public class TestClientRequestExecution extends IntegrationTestBase {
String s = "http://localhost:" + port;
HttpGet httpget = new HttpGet(s);
this.httpclient = new HttpClientBuilder().build();
this.httpclient = HttpClients.custom().build();
String virtHost = "virtual";
httpget.getParams().setParameter(ClientPNames.VIRTUAL_HOST, new HttpHost(virtHost, port));
HttpResponse response = this.httpclient.execute(getServerHttp(), httpget, context);
@ -166,7 +166,7 @@ public class TestClientRequestExecution extends IntegrationTestBase {
String s = "http://localhost:" + port;
HttpGet httpget = new HttpGet(s);
this.httpclient = new HttpClientBuilder().build();
this.httpclient = HttpClients.custom().build();
String virtHost = "virtual";
int virtPort = 9876;
httpget.getParams().setParameter(ClientPNames.VIRTUAL_HOST, new HttpHost(virtHost, virtPort));
@ -194,7 +194,7 @@ public class TestClientRequestExecution extends IntegrationTestBase {
String s = "http://localhost:" + port;
HttpGet httpget = new HttpGet(s);
this.httpclient = new HttpClientBuilder().build();
this.httpclient = HttpClients.custom().build();
String virtHost = "virtual";
this.httpclient.getParams().setParameter(ClientPNames.VIRTUAL_HOST, new HttpHost(virtHost, port));
HttpResponse response = this.httpclient.execute(getServerHttp(), httpget, context);
@ -219,7 +219,7 @@ public class TestClientRequestExecution extends IntegrationTestBase {
HttpHost target1 = new HttpHost("whatever", 80);
HttpHost target2 = new HttpHost("localhost", port);
this.httpclient = new HttpClientBuilder().build();
this.httpclient = HttpClients.custom().build();
this.httpclient.getParams().setParameter(ClientPNames.DEFAULT_HOST, target1);
String s = "/path";
@ -284,7 +284,7 @@ public class TestClientRequestExecution extends IntegrationTestBase {
};
this.httpclient = new HttpClientBuilder()
this.httpclient = HttpClients.custom()
.addInterceptorFirst(interceptor)
.setRequestExecutor(new FaultyHttpRequestExecutor("Oppsie"))
.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"))
.setRetryHandler(requestRetryHandler)
.build();

View File

@ -40,12 +40,12 @@ import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
import org.apache.http.MalformedChunkCodingException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.ConnectionRequest;
import org.apache.http.conn.ConnectionPoolTimeoutException;
import org.apache.http.conn.ConnectionRequest;
import org.apache.http.conn.routing.HttpRoute;
import org.apache.http.entity.BasicHttpEntity;
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.pool.PoolStats;
import org.apache.http.protocol.ExecutionContext;
@ -64,7 +64,7 @@ public class TestConnectionAutoRelease extends IntegrationTestBase {
public void setUp() throws Exception {
startServer();
this.mgr = new PoolingHttpClientConnectionManager();
this.httpclient = new HttpClientBuilder().setConnectionManager(this.mgr).build();
this.httpclient = HttpClients.custom().setConnectionManager(this.mgr).build();
}
@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.StringEntity;
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.protocol.HttpContext;
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");
HttpResponse response = this.httpclient.execute(getServerHttp(), request);
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.httpclient = new HttpClientBuilder().build();
this.httpclient = HttpClients.custom().build();
HttpGet request = new HttpGet("/some-resource");
HttpResponse response = this.httpclient.execute(getServerHttp(), request);
@ -136,7 +136,7 @@ public class TestContentCodings extends IntegrationTestBase {
this.localServer.register("*", createDeflateEncodingRequestHandler(entityText, true));
this.httpclient = new HttpClientBuilder().build();
this.httpclient = HttpClients.custom().build();
HttpGet request = new HttpGet("/some-resource");
HttpResponse response = this.httpclient.execute(getServerHttp(), request);
@ -155,7 +155,7 @@ public class TestContentCodings extends IntegrationTestBase {
this.localServer.register("*", createGzipEncodingRequestHandler(entityText));
this.httpclient = new HttpClientBuilder().build();
this.httpclient = HttpClients.custom().build();
HttpGet request = new HttpGet("/some-resource");
HttpResponse response = this.httpclient.execute(getServerHttp(), request);
@ -184,7 +184,7 @@ public class TestContentCodings extends IntegrationTestBase {
PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
cm.setMaxTotal(clients);
this.httpclient = new HttpClientBuilder().setConnectionManager(cm).build();
this.httpclient = HttpClients.custom().setConnectionManager(cm).build();
ExecutorService executor = Executors.newFixedThreadPool(clients);
@ -228,7 +228,7 @@ public class TestContentCodings extends IntegrationTestBase {
this.localServer.register("*", createGzipEncodingRequestHandler(entityText));
this.httpclient = new HttpClientBuilder().build();
this.httpclient = HttpClients.custom().build();
HttpGet request = new HttpGet("/some-resource");
HttpResponse response = this.httpclient.execute(getServerHttp(), request);
@ -251,7 +251,7 @@ public class TestContentCodings extends IntegrationTestBase {
this.localServer.register("*", createDeflateEncodingRequestHandler(entityText, true));
this.httpclient = new HttpClientBuilder().build();
this.httpclient = HttpClients.custom().build();
HttpGet request = new HttpGet("/some-resource");
HttpResponse response = this.httpclient.execute(getServerHttp(), request);
@ -268,7 +268,7 @@ public class TestContentCodings extends IntegrationTestBase {
this.localServer.register("*", createGzipEncodingRequestHandler(entityText));
this.httpclient = new HttpClientBuilder().build();
this.httpclient = HttpClients.custom().build();
HttpGet request = new HttpGet("/some-resource");
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.httpclient = new HttpClientBuilder().build();
this.httpclient = HttpClients.custom().build();
HttpGet request = new HttpGet("/some-resource");
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.entity.StringEntity;
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.protocol.BasicHttpContext;
import org.apache.http.protocol.ExecutionContext;
@ -64,7 +64,7 @@ public class TestCookie2Support extends IntegrationTestBase {
@Before
public void setUp() throws Exception {
startServer();
this.httpclient = new HttpClientBuilder().build();
this.httpclient = HttpClients.custom().build();
}
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.HttpUriRequest;
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.localserver.LocalServerTestBase;
import org.apache.http.localserver.LocalTestServer;
@ -60,7 +60,7 @@ public class TestIdleConnectionEviction extends LocalServerTestBase {
cm.setDefaultMaxPerRoute(10);
cm.setMaxTotal(50);
HttpClient httpclient = new HttpClientBuilder().setConnectionManager(cm).build();
HttpClient httpclient = HttpClients.custom().setConnectionManager(cm).build();
IdleConnectionMonitor idleConnectionMonitor = new IdleConnectionMonitor(cm);
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.entity.StringEntity;
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.message.BasicHeader;
import org.apache.http.protocol.BasicHttpContext;
@ -71,7 +71,7 @@ public class TestRedirects extends IntegrationTestBase {
@Before
public void setUp() throws Exception {
startServer();
this.httpclient = new HttpClientBuilder().build();
this.httpclient = HttpClients.createDefault();
}
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.SPNegoSchemeFactory;
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.params.HttpParams;
import org.apache.http.protocol.HttpContext;
import org.apache.http.protocol.HttpRequestHandler;
import org.apache.http.util.EntityUtils;
import org.ietf.jgss.GSSContext;
import org.ietf.jgss.GSSCredential;
import org.ietf.jgss.GSSManager;
@ -64,7 +63,7 @@ import org.mockito.Matchers;
import org.mockito.Mockito;
/**
* Tests for {@link NegotiateScheme}.
* Tests for {@link SPNegoScheme}.
*/
public class TestSPNegoScheme extends IntegrationTestBase {
@ -164,7 +163,7 @@ public class TestSPNegoScheme extends IntegrationTestBase {
Credentials use_jaas_creds = new UseJaasCredentials();
credentialsProvider.setCredentials(new AuthScope(null, -1, null), use_jaas_creds);
this.httpclient = new HttpClientBuilder()
this.httpclient = HttpClients.custom()
.registerAuthScheme(AuthPolicy.SPNEGO, nsf)
.setCredentialsProvider(credentialsProvider)
.build();
@ -196,7 +195,7 @@ public class TestSPNegoScheme extends IntegrationTestBase {
Credentials use_jaas_creds = new UseJaasCredentials();
credentialsProvider.setCredentials(new AuthScope(null, -1, null), use_jaas_creds);
this.httpclient = new HttpClientBuilder()
this.httpclient = HttpClients.custom()
.registerAuthScheme(AuthPolicy.SPNEGO, nsf)
.setCredentialsProvider(credentialsProvider)
.build();

View File

@ -37,7 +37,7 @@ import org.apache.http.client.HttpClient;
import org.apache.http.client.UserTokenHandler;
import org.apache.http.client.methods.HttpGet;
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.params.BasicHttpParams;
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)
.setUserTokenHandler(userTokenHandler)
.build();
@ -235,7 +235,7 @@ public class TestStatefulConnManagement extends IntegrationTestBase {
};
this.httpclient = new HttpClientBuilder()
this.httpclient = HttpClients.custom()
.setConnectionManager(connMngr)
.setUserTokenHandler(userTokenHandler)
.build();