mirror of
https://github.com/apache/httpcomponents-client.git
synced 2025-02-25 19:55:35 +00:00
TABS -> SPACES
git-svn-id: https://svn.apache.org/repos/asf/httpcomponents/httpclient/trunk@1026121 13f79535-47bb-0310-9956-ffa450edef68
This commit is contained in:
parent
e8bb17f4e2
commit
6d67c55306
@ -41,7 +41,7 @@ public class ClientAbortMethod {
|
|||||||
public final static void main(String[] args) throws Exception {
|
public final static void main(String[] args) throws Exception {
|
||||||
HttpClient httpclient = new DefaultHttpClient();
|
HttpClient httpclient = new DefaultHttpClient();
|
||||||
|
|
||||||
HttpGet httpget = new HttpGet("http://www.apache.org/");
|
HttpGet httpget = new HttpGet("http://www.apache.org/");
|
||||||
|
|
||||||
System.out.println("executing request " + httpget.getURI());
|
System.out.println("executing request " + httpget.getURI());
|
||||||
HttpResponse response = httpclient.execute(httpget);
|
HttpResponse response = httpclient.execute(httpget);
|
||||||
@ -57,11 +57,11 @@ public final static void main(String[] args) throws Exception {
|
|||||||
// Do not feel like reading the response body
|
// Do not feel like reading the response body
|
||||||
// Call abort on the request object
|
// Call abort on the request object
|
||||||
httpget.abort();
|
httpget.abort();
|
||||||
|
|
||||||
// When HttpClient instance is no longer needed,
|
// When HttpClient instance is no longer needed,
|
||||||
// shut down the connection manager to ensure
|
// shut down the connection manager to ensure
|
||||||
// immediate deallocation of all system resources
|
// immediate deallocation of all system resources
|
||||||
httpclient.getConnectionManager().shutdown();
|
httpclient.getConnectionManager().shutdown();
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
@ -35,7 +35,7 @@
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* A simple example that uses HttpClient to execute an HTTP request against
|
* A simple example that uses HttpClient to execute an HTTP request against
|
||||||
* a target site that requires user authentication.
|
* a target site that requires user authentication.
|
||||||
*/
|
*/
|
||||||
public class ClientAuthentication {
|
public class ClientAuthentication {
|
||||||
|
|
||||||
@ -43,11 +43,11 @@ public static void main(String[] args) throws Exception {
|
|||||||
DefaultHttpClient httpclient = new DefaultHttpClient();
|
DefaultHttpClient httpclient = new DefaultHttpClient();
|
||||||
|
|
||||||
httpclient.getCredentialsProvider().setCredentials(
|
httpclient.getCredentialsProvider().setCredentials(
|
||||||
new AuthScope("localhost", 443),
|
new AuthScope("localhost", 443),
|
||||||
new UsernamePasswordCredentials("username", "password"));
|
new UsernamePasswordCredentials("username", "password"));
|
||||||
|
|
||||||
HttpGet httpget = new HttpGet("https://localhost/protected");
|
HttpGet httpget = new HttpGet("https://localhost/protected");
|
||||||
|
|
||||||
System.out.println("executing request" + httpget.getRequestLine());
|
System.out.println("executing request" + httpget.getRequestLine());
|
||||||
HttpResponse response = httpclient.execute(httpget);
|
HttpResponse response = httpclient.execute(httpget);
|
||||||
HttpEntity entity = response.getEntity();
|
HttpEntity entity = response.getEntity();
|
||||||
@ -59,9 +59,9 @@ public static void main(String[] args) throws Exception {
|
|||||||
}
|
}
|
||||||
EntityUtils.consume(entity);
|
EntityUtils.consume(entity);
|
||||||
|
|
||||||
// When HttpClient instance is no longer needed,
|
// When HttpClient instance is no longer needed,
|
||||||
// shut down the connection manager to ensure
|
// shut down the connection manager to ensure
|
||||||
// immediate deallocation of all system resources
|
// immediate deallocation of all system resources
|
||||||
httpclient.getConnectionManager().shutdown();
|
httpclient.getConnectionManager().shutdown();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -21,7 +21,7 @@
|
|||||||
* individuals on behalf of the Apache Software Foundation. For more
|
* individuals on behalf of the Apache Software Foundation. For more
|
||||||
* information on the Apache Software Foundation, please see
|
* information on the Apache Software Foundation, please see
|
||||||
* <http://www.apache.org/>.
|
* <http://www.apache.org/>.
|
||||||
*
|
*
|
||||||
*/
|
*/
|
||||||
|
|
||||||
package org.apache.http.examples.client;
|
package org.apache.http.examples.client;
|
||||||
@ -58,14 +58,14 @@ public static void main(String[] args) throws Exception {
|
|||||||
new FileInputStream(file), -1);
|
new FileInputStream(file), -1);
|
||||||
reqEntity.setContentType("binary/octet-stream");
|
reqEntity.setContentType("binary/octet-stream");
|
||||||
reqEntity.setChunked(true);
|
reqEntity.setChunked(true);
|
||||||
// It may be more appropriate to use FileEntity class in this particular
|
// It may be more appropriate to use FileEntity class in this particular
|
||||||
// instance but we are using a more generic InputStreamEntity to demonstrate
|
// instance but we are using a more generic InputStreamEntity to demonstrate
|
||||||
// the capability to stream out data from any arbitrary source
|
// the capability to stream out data from any arbitrary source
|
||||||
//
|
//
|
||||||
// FileEntity entity = new FileEntity(file, "binary/octet-stream");
|
// FileEntity entity = new FileEntity(file, "binary/octet-stream");
|
||||||
|
|
||||||
httppost.setEntity(reqEntity);
|
httppost.setEntity(reqEntity);
|
||||||
|
|
||||||
System.out.println("executing request " + httppost.getRequestLine());
|
System.out.println("executing request " + httppost.getRequestLine());
|
||||||
HttpResponse response = httpclient.execute(httppost);
|
HttpResponse response = httpclient.execute(httppost);
|
||||||
HttpEntity resEntity = response.getEntity();
|
HttpEntity resEntity = response.getEntity();
|
||||||
@ -78,10 +78,10 @@ public static void main(String[] args) throws Exception {
|
|||||||
}
|
}
|
||||||
EntityUtils.consume(resEntity);
|
EntityUtils.consume(resEntity);
|
||||||
|
|
||||||
// When HttpClient instance is no longer needed,
|
// When HttpClient instance is no longer needed,
|
||||||
// shut down the connection manager to ensure
|
// shut down the connection manager to ensure
|
||||||
// immediate deallocation of all system resources
|
// immediate deallocation of all system resources
|
||||||
httpclient.getConnectionManager().shutdown();
|
httpclient.getConnectionManager().shutdown();
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
@ -44,24 +44,24 @@
|
|||||||
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* This example demonstrates the use of a local HTTP context populated with
|
* This example demonstrates the use of a local HTTP context populated with
|
||||||
* custom attributes.
|
* custom attributes.
|
||||||
*/
|
*/
|
||||||
public class ClientCustomContext {
|
public class ClientCustomContext {
|
||||||
|
|
||||||
public final static void main(String[] args) throws Exception {
|
public final static void main(String[] args) throws Exception {
|
||||||
|
|
||||||
HttpClient httpclient = new DefaultHttpClient();
|
HttpClient httpclient = new DefaultHttpClient();
|
||||||
|
|
||||||
// Create a local instance of cookie store
|
// Create a local instance of cookie store
|
||||||
CookieStore cookieStore = new BasicCookieStore();
|
CookieStore cookieStore = new BasicCookieStore();
|
||||||
|
|
||||||
// Create local HTTP context
|
// Create local HTTP context
|
||||||
HttpContext localContext = new BasicHttpContext();
|
HttpContext localContext = new BasicHttpContext();
|
||||||
// Bind custom cookie store to the local context
|
// Bind custom cookie store to the local context
|
||||||
localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
|
localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
|
||||||
|
|
||||||
HttpGet httpget = new HttpGet("http://www.google.com/");
|
HttpGet httpget = new HttpGet("http://www.google.com/");
|
||||||
|
|
||||||
System.out.println("executing request " + httpget.getURI());
|
System.out.println("executing request " + httpget.getURI());
|
||||||
|
|
||||||
@ -78,17 +78,17 @@ public final static void main(String[] args) throws Exception {
|
|||||||
for (int i = 0; i < cookies.size(); i++) {
|
for (int i = 0; i < cookies.size(); i++) {
|
||||||
System.out.println("Local cookie: " + cookies.get(i));
|
System.out.println("Local cookie: " + cookies.get(i));
|
||||||
}
|
}
|
||||||
|
|
||||||
// Consume response content
|
// Consume response content
|
||||||
EntityUtils.consume(entity);
|
EntityUtils.consume(entity);
|
||||||
|
|
||||||
System.out.println("----------------------------------------");
|
System.out.println("----------------------------------------");
|
||||||
|
|
||||||
// When HttpClient instance is no longer needed,
|
// When HttpClient instance is no longer needed,
|
||||||
// shut down the connection manager to ensure
|
// shut down the connection manager to ensure
|
||||||
// immediate deallocation of all system resources
|
// immediate deallocation of all system resources
|
||||||
httpclient.getConnectionManager().shutdown();
|
httpclient.getConnectionManager().shutdown();
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -47,14 +47,14 @@ public class ClientCustomSSL {
|
|||||||
public final static void main(String[] args) throws Exception {
|
public final static void main(String[] args) throws Exception {
|
||||||
DefaultHttpClient httpclient = new DefaultHttpClient();
|
DefaultHttpClient httpclient = new DefaultHttpClient();
|
||||||
|
|
||||||
KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
|
KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
|
||||||
FileInputStream instream = new FileInputStream(new File("my.keystore"));
|
FileInputStream instream = new FileInputStream(new File("my.keystore"));
|
||||||
try {
|
try {
|
||||||
trustStore.load(instream, "nopassword".toCharArray());
|
trustStore.load(instream, "nopassword".toCharArray());
|
||||||
} finally {
|
} finally {
|
||||||
instream.close();
|
instream.close();
|
||||||
}
|
}
|
||||||
|
|
||||||
SSLSocketFactory socketFactory = new SSLSocketFactory(trustStore);
|
SSLSocketFactory socketFactory = new SSLSocketFactory(trustStore);
|
||||||
Scheme sch = new Scheme("https", 443, socketFactory);
|
Scheme sch = new Scheme("https", 443, socketFactory);
|
||||||
httpclient.getConnectionManager().getSchemeRegistry().register(sch);
|
httpclient.getConnectionManager().getSchemeRegistry().register(sch);
|
||||||
@ -62,7 +62,7 @@ public final static void main(String[] args) throws Exception {
|
|||||||
HttpGet httpget = new HttpGet("https://localhost/");
|
HttpGet httpget = new HttpGet("https://localhost/");
|
||||||
|
|
||||||
System.out.println("executing request" + httpget.getRequestLine());
|
System.out.println("executing request" + httpget.getRequestLine());
|
||||||
|
|
||||||
HttpResponse response = httpclient.execute(httpget);
|
HttpResponse response = httpclient.execute(httpget);
|
||||||
HttpEntity entity = response.getEntity();
|
HttpEntity entity = response.getEntity();
|
||||||
|
|
||||||
@ -73,10 +73,10 @@ public final static void main(String[] args) throws Exception {
|
|||||||
}
|
}
|
||||||
EntityUtils.consume(entity);
|
EntityUtils.consume(entity);
|
||||||
|
|
||||||
// When HttpClient instance is no longer needed,
|
// When HttpClient instance is no longer needed,
|
||||||
// shut down the connection manager to ensure
|
// shut down the connection manager to ensure
|
||||||
// immediate deallocation of all system resources
|
// immediate deallocation of all system resources
|
||||||
httpclient.getConnectionManager().shutdown();
|
httpclient.getConnectionManager().shutdown();
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
@ -23,7 +23,7 @@
|
|||||||
* <http://www.apache.org/>.
|
* <http://www.apache.org/>.
|
||||||
*
|
*
|
||||||
*/
|
*/
|
||||||
|
|
||||||
package org.apache.http.examples.client;
|
package org.apache.http.examples.client;
|
||||||
|
|
||||||
import java.util.concurrent.TimeUnit;
|
import java.util.concurrent.TimeUnit;
|
||||||
@ -47,16 +47,16 @@
|
|||||||
public class ClientEvictExpiredConnections {
|
public class ClientEvictExpiredConnections {
|
||||||
|
|
||||||
public static void main(String[] args) throws Exception {
|
public static void main(String[] args) throws Exception {
|
||||||
// Create and initialize scheme registry
|
// Create and initialize scheme registry
|
||||||
SchemeRegistry schemeRegistry = new SchemeRegistry();
|
SchemeRegistry schemeRegistry = new SchemeRegistry();
|
||||||
schemeRegistry.register(
|
schemeRegistry.register(
|
||||||
new Scheme("http", 80, PlainSocketFactory.getSocketFactory()));
|
new Scheme("http", 80, PlainSocketFactory.getSocketFactory()));
|
||||||
|
|
||||||
ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager(schemeRegistry);
|
ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager(schemeRegistry);
|
||||||
cm.setMaxTotal(100);
|
cm.setMaxTotal(100);
|
||||||
|
|
||||||
HttpClient httpclient = new DefaultHttpClient(cm);
|
HttpClient httpclient = new DefaultHttpClient(cm);
|
||||||
|
|
||||||
// create an array of URIs to perform GETs on
|
// create an array of URIs to perform GETs on
|
||||||
String[] urisToGet = {
|
String[] urisToGet = {
|
||||||
"http://jakarta.apache.org/",
|
"http://jakarta.apache.org/",
|
||||||
@ -64,10 +64,10 @@ public static void main(String[] args) throws Exception {
|
|||||||
"http://jakarta.apache.org/commons/httpclient/",
|
"http://jakarta.apache.org/commons/httpclient/",
|
||||||
"http://svn.apache.org/viewvc/jakarta/httpcomponents/"
|
"http://svn.apache.org/viewvc/jakarta/httpcomponents/"
|
||||||
};
|
};
|
||||||
|
|
||||||
IdleConnectionEvictor connEvictor = new IdleConnectionEvictor(cm);
|
IdleConnectionEvictor connEvictor = new IdleConnectionEvictor(cm);
|
||||||
connEvictor.start();
|
connEvictor.start();
|
||||||
|
|
||||||
for (int i = 0; i < urisToGet.length; i++) {
|
for (int i = 0; i < urisToGet.length; i++) {
|
||||||
String requestURI = urisToGet[i];
|
String requestURI = urisToGet[i];
|
||||||
HttpGet req = new HttpGet(requestURI);
|
HttpGet req = new HttpGet(requestURI);
|
||||||
@ -86,26 +86,26 @@ public static void main(String[] args) throws Exception {
|
|||||||
|
|
||||||
EntityUtils.consume(entity);
|
EntityUtils.consume(entity);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Sleep 10 sec and let the connection evictor do its job
|
// Sleep 10 sec and let the connection evictor do its job
|
||||||
Thread.sleep(20000);
|
Thread.sleep(20000);
|
||||||
|
|
||||||
// Shut down the evictor thread
|
// Shut down the evictor thread
|
||||||
connEvictor.shutdown();
|
connEvictor.shutdown();
|
||||||
connEvictor.join();
|
connEvictor.join();
|
||||||
|
|
||||||
// When HttpClient instance is no longer needed,
|
// When HttpClient instance is no longer needed,
|
||||||
// shut down the connection manager to ensure
|
// shut down the connection manager to ensure
|
||||||
// immediate deallocation of all system resources
|
// immediate deallocation of all system resources
|
||||||
httpclient.getConnectionManager().shutdown();
|
httpclient.getConnectionManager().shutdown();
|
||||||
}
|
}
|
||||||
|
|
||||||
public static class IdleConnectionEvictor extends Thread {
|
public static class IdleConnectionEvictor extends Thread {
|
||||||
|
|
||||||
private final ClientConnectionManager connMgr;
|
private final ClientConnectionManager connMgr;
|
||||||
|
|
||||||
private volatile boolean shutdown;
|
private volatile boolean shutdown;
|
||||||
|
|
||||||
public IdleConnectionEvictor(ClientConnectionManager connMgr) {
|
public IdleConnectionEvictor(ClientConnectionManager connMgr) {
|
||||||
super();
|
super();
|
||||||
this.connMgr = connMgr;
|
this.connMgr = connMgr;
|
||||||
@ -128,14 +128,14 @@ public void run() {
|
|||||||
// terminate
|
// terminate
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public void shutdown() {
|
public void shutdown() {
|
||||||
shutdown = true;
|
shutdown = true;
|
||||||
synchronized (this) {
|
synchronized (this) {
|
||||||
notifyAll();
|
notifyAll();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
@ -38,7 +38,7 @@
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* How to send a request directly using {@link HttpClient}.
|
* How to send a request directly using {@link HttpClient}.
|
||||||
*
|
*
|
||||||
* @since 4.0
|
* @since 4.0
|
||||||
*/
|
*/
|
||||||
public class ClientExecuteDirect {
|
public class ClientExecuteDirect {
|
||||||
@ -66,10 +66,10 @@ public static void main(String[] args) throws Exception {
|
|||||||
System.out.println(EntityUtils.toString(entity));
|
System.out.println(EntityUtils.toString(entity));
|
||||||
}
|
}
|
||||||
|
|
||||||
// When HttpClient instance is no longer needed,
|
// When HttpClient instance is no longer needed,
|
||||||
// shut down the connection manager to ensure
|
// shut down the connection manager to ensure
|
||||||
// immediate deallocation of all system resources
|
// immediate deallocation of all system resources
|
||||||
httpclient.getConnectionManager().shutdown();
|
httpclient.getConnectionManager().shutdown();
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
@ -69,10 +69,10 @@ public static void main(String[] args)throws Exception {
|
|||||||
System.out.println(EntityUtils.toString(entity));
|
System.out.println(EntityUtils.toString(entity));
|
||||||
}
|
}
|
||||||
|
|
||||||
// When HttpClient instance is no longer needed,
|
// When HttpClient instance is no longer needed,
|
||||||
// shut down the connection manager to ensure
|
// shut down the connection manager to ensure
|
||||||
// immediate deallocation of all system resources
|
// immediate deallocation of all system resources
|
||||||
httpclient.getConnectionManager().shutdown();
|
httpclient.getConnectionManager().shutdown();
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
@ -81,12 +81,12 @@ public static void main(String[] args)throws Exception {
|
|||||||
System.out.println(EntityUtils.toString(entity));
|
System.out.println(EntityUtils.toString(entity));
|
||||||
}
|
}
|
||||||
|
|
||||||
// When HttpClient instance is no longer needed,
|
// When HttpClient instance is no longer needed,
|
||||||
// shut down the connection manager to ensure
|
// shut down the connection manager to ensure
|
||||||
// immediate deallocation of all system resources
|
// immediate deallocation of all system resources
|
||||||
httpclient.getConnectionManager().shutdown();
|
httpclient.getConnectionManager().shutdown();
|
||||||
}
|
}
|
||||||
|
|
||||||
static class MySchemeSocketFactory implements SchemeSocketFactory {
|
static class MySchemeSocketFactory implements SchemeSocketFactory {
|
||||||
|
|
||||||
public Socket createSocket(final HttpParams params) throws IOException {
|
public Socket createSocket(final HttpParams params) throws IOException {
|
||||||
@ -96,16 +96,16 @@ public Socket createSocket(final HttpParams params) throws IOException {
|
|||||||
String proxyHost = (String) params.getParameter("socks.host");
|
String proxyHost = (String) params.getParameter("socks.host");
|
||||||
Integer proxyPort = (Integer) params.getParameter("socks.port");
|
Integer proxyPort = (Integer) params.getParameter("socks.port");
|
||||||
|
|
||||||
InetSocketAddress socksaddr = new InetSocketAddress(proxyHost, proxyPort);
|
InetSocketAddress socksaddr = new InetSocketAddress(proxyHost, proxyPort);
|
||||||
Proxy proxy = new Proxy(Proxy.Type.SOCKS, socksaddr);
|
Proxy proxy = new Proxy(Proxy.Type.SOCKS, socksaddr);
|
||||||
return new Socket(proxy);
|
return new Socket(proxy);
|
||||||
}
|
}
|
||||||
|
|
||||||
public Socket connectSocket(
|
public Socket connectSocket(
|
||||||
final Socket socket,
|
final Socket socket,
|
||||||
final InetSocketAddress remoteAddress,
|
final InetSocketAddress remoteAddress,
|
||||||
final InetSocketAddress localAddress,
|
final InetSocketAddress localAddress,
|
||||||
final HttpParams params)
|
final HttpParams params)
|
||||||
throws IOException, UnknownHostException, ConnectTimeoutException {
|
throws IOException, UnknownHostException, ConnectTimeoutException {
|
||||||
if (remoteAddress == null) {
|
if (remoteAddress == null) {
|
||||||
throw new IllegalArgumentException("Remote address may not be null");
|
throw new IllegalArgumentException("Remote address may not be null");
|
||||||
@ -127,7 +127,7 @@ public Socket connectSocket(
|
|||||||
try {
|
try {
|
||||||
sock.connect(remoteAddress, timeout);
|
sock.connect(remoteAddress, timeout);
|
||||||
} catch (SocketTimeoutException ex) {
|
} catch (SocketTimeoutException ex) {
|
||||||
throw new ConnectTimeoutException("Connect to " + remoteAddress.getHostName() + "/"
|
throw new ConnectTimeoutException("Connect to " + remoteAddress.getHostName() + "/"
|
||||||
+ remoteAddress.getAddress() + " timed out");
|
+ remoteAddress.getAddress() + " timed out");
|
||||||
}
|
}
|
||||||
return sock;
|
return sock;
|
||||||
@ -136,7 +136,7 @@ public Socket connectSocket(
|
|||||||
public boolean isSecure(final Socket sock) throws IllegalArgumentException {
|
public boolean isSecure(final Socket sock) throws IllegalArgumentException {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
@ -95,9 +95,9 @@ public static void main(String[] args) throws Exception {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// When HttpClient instance is no longer needed,
|
// When HttpClient instance is no longer needed,
|
||||||
// shut down the connection manager to ensure
|
// shut down the connection manager to ensure
|
||||||
// immediate deallocation of all system resources
|
// immediate deallocation of all system resources
|
||||||
httpclient.getConnectionManager().shutdown();
|
httpclient.getConnectionManager().shutdown();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -46,15 +46,15 @@
|
|||||||
import org.apache.http.util.EntityUtils;
|
import org.apache.http.util.EntityUtils;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Demonstration of the use of protocol interceptors to transparently
|
* Demonstration of the use of protocol interceptors to transparently
|
||||||
* modify properties of HTTP messages sent / received by the HTTP client.
|
* modify properties of HTTP messages sent / received by the HTTP client.
|
||||||
* <p/>
|
* <p/>
|
||||||
* In this particular case HTTP client is made capable of transparent content
|
* In this particular case HTTP client is made capable of transparent content
|
||||||
* GZIP compression by adding two protocol interceptors: a request interceptor
|
* GZIP compression by adding two protocol interceptors: a request interceptor
|
||||||
* that adds 'Accept-Encoding: gzip' header to all outgoing requests and
|
* that adds 'Accept-Encoding: gzip' header to all outgoing requests and
|
||||||
* a response interceptor that automatically expands compressed response
|
* a response interceptor that automatically expands compressed response
|
||||||
* entities by wrapping them with a uncompressing decorator class. The use of
|
* entities by wrapping them with a uncompressing decorator class. The use of
|
||||||
* protocol interceptors makes content compression completely transparent to
|
* protocol interceptors makes content compression completely transparent to
|
||||||
* the consumer of the {@link org.apache.http.client.HttpClient HttpClient}
|
* the consumer of the {@link org.apache.http.client.HttpClient HttpClient}
|
||||||
* interface.
|
* interface.
|
||||||
*/
|
*/
|
||||||
@ -64,9 +64,9 @@ public final static void main(String[] args) throws Exception {
|
|||||||
DefaultHttpClient httpclient = new DefaultHttpClient();
|
DefaultHttpClient httpclient = new DefaultHttpClient();
|
||||||
|
|
||||||
httpclient.addRequestInterceptor(new HttpRequestInterceptor() {
|
httpclient.addRequestInterceptor(new HttpRequestInterceptor() {
|
||||||
|
|
||||||
public void process(
|
public void process(
|
||||||
final HttpRequest request,
|
final HttpRequest request,
|
||||||
final HttpContext context) throws HttpException, IOException {
|
final HttpContext context) throws HttpException, IOException {
|
||||||
if (!request.containsHeader("Accept-Encoding")) {
|
if (!request.containsHeader("Accept-Encoding")) {
|
||||||
request.addHeader("Accept-Encoding", "gzip");
|
request.addHeader("Accept-Encoding", "gzip");
|
||||||
@ -74,11 +74,11 @@ public void process(
|
|||||||
}
|
}
|
||||||
|
|
||||||
});
|
});
|
||||||
|
|
||||||
httpclient.addResponseInterceptor(new HttpResponseInterceptor() {
|
httpclient.addResponseInterceptor(new HttpResponseInterceptor() {
|
||||||
|
|
||||||
public void process(
|
public void process(
|
||||||
final HttpResponse response,
|
final HttpResponse response,
|
||||||
final HttpContext context) throws HttpException, IOException {
|
final HttpContext context) throws HttpException, IOException {
|
||||||
HttpEntity entity = response.getEntity();
|
HttpEntity entity = response.getEntity();
|
||||||
Header ceheader = entity.getContentEncoding();
|
Header ceheader = entity.getContentEncoding();
|
||||||
@ -87,17 +87,17 @@ public void process(
|
|||||||
for (int i = 0; i < codecs.length; i++) {
|
for (int i = 0; i < codecs.length; i++) {
|
||||||
if (codecs[i].getName().equalsIgnoreCase("gzip")) {
|
if (codecs[i].getName().equalsIgnoreCase("gzip")) {
|
||||||
response.setEntity(
|
response.setEntity(
|
||||||
new GzipDecompressingEntity(response.getEntity()));
|
new GzipDecompressingEntity(response.getEntity()));
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
});
|
});
|
||||||
|
|
||||||
HttpGet httpget = new HttpGet("http://www.apache.org/");
|
HttpGet httpget = new HttpGet("http://www.apache.org/");
|
||||||
|
|
||||||
// Execute HTTP request
|
// Execute HTTP request
|
||||||
System.out.println("executing request " + httpget.getURI());
|
System.out.println("executing request " + httpget.getURI());
|
||||||
HttpResponse response = httpclient.execute(httpget);
|
HttpResponse response = httpclient.execute(httpget);
|
||||||
@ -109,7 +109,7 @@ public void process(
|
|||||||
System.out.println("----------------------------------------");
|
System.out.println("----------------------------------------");
|
||||||
|
|
||||||
HttpEntity entity = response.getEntity();
|
HttpEntity entity = response.getEntity();
|
||||||
|
|
||||||
if (entity != null) {
|
if (entity != null) {
|
||||||
String content = EntityUtils.toString(entity);
|
String content = EntityUtils.toString(entity);
|
||||||
System.out.println(content);
|
System.out.println(content);
|
||||||
@ -117,10 +117,10 @@ public void process(
|
|||||||
System.out.println("Uncompressed size: "+content.length());
|
System.out.println("Uncompressed size: "+content.length());
|
||||||
}
|
}
|
||||||
|
|
||||||
// When HttpClient instance is no longer needed,
|
// When HttpClient instance is no longer needed,
|
||||||
// shut down the connection manager to ensure
|
// shut down the connection manager to ensure
|
||||||
// immediate deallocation of all system resources
|
// immediate deallocation of all system resources
|
||||||
httpclient.getConnectionManager().shutdown();
|
httpclient.getConnectionManager().shutdown();
|
||||||
}
|
}
|
||||||
|
|
||||||
static class GzipDecompressingEntity extends HttpEntityWrapper {
|
static class GzipDecompressingEntity extends HttpEntityWrapper {
|
||||||
@ -128,7 +128,7 @@ static class GzipDecompressingEntity extends HttpEntityWrapper {
|
|||||||
public GzipDecompressingEntity(final HttpEntity entity) {
|
public GzipDecompressingEntity(final HttpEntity entity) {
|
||||||
super(entity);
|
super(entity);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public InputStream getContent()
|
public InputStream getContent()
|
||||||
throws IOException, IllegalStateException {
|
throws IOException, IllegalStateException {
|
||||||
@ -145,7 +145,7 @@ public long getContentLength() {
|
|||||||
return -1;
|
return -1;
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -44,7 +44,7 @@
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* A simple example that uses HttpClient to execute an HTTP request against
|
* A simple example that uses HttpClient to execute an HTTP request against
|
||||||
* a target site that requires user authentication.
|
* a target site that requires user authentication.
|
||||||
*/
|
*/
|
||||||
public class ClientInteractiveAuthentication {
|
public class ClientInteractiveAuthentication {
|
||||||
|
|
||||||
@ -55,7 +55,7 @@ public static void main(String[] args) throws Exception {
|
|||||||
HttpContext localContext = new BasicHttpContext();
|
HttpContext localContext = new BasicHttpContext();
|
||||||
|
|
||||||
HttpGet httpget = new HttpGet("http://localhost/test");
|
HttpGet httpget = new HttpGet("http://localhost/test");
|
||||||
|
|
||||||
boolean trying = true;
|
boolean trying = true;
|
||||||
while (trying) {
|
while (trying) {
|
||||||
System.out.println("executing request " + httpget.getRequestLine());
|
System.out.println("executing request " + httpget.getRequestLine());
|
||||||
@ -67,34 +67,34 @@ public static void main(String[] args) throws Exception {
|
|||||||
// Consume response content
|
// Consume response content
|
||||||
HttpEntity entity = response.getEntity();
|
HttpEntity entity = response.getEntity();
|
||||||
EntityUtils.consume(entity);
|
EntityUtils.consume(entity);
|
||||||
|
|
||||||
int sc = response.getStatusLine().getStatusCode();
|
int sc = response.getStatusLine().getStatusCode();
|
||||||
|
|
||||||
AuthState authState = null;
|
AuthState authState = null;
|
||||||
if (sc == HttpStatus.SC_UNAUTHORIZED) {
|
if (sc == HttpStatus.SC_UNAUTHORIZED) {
|
||||||
// Target host authentication required
|
// Target host authentication required
|
||||||
authState = (AuthState) localContext.getAttribute(ClientContext.TARGET_AUTH_STATE);
|
authState = (AuthState) localContext.getAttribute(ClientContext.TARGET_AUTH_STATE);
|
||||||
}
|
}
|
||||||
if (sc == HttpStatus.SC_PROXY_AUTHENTICATION_REQUIRED) {
|
if (sc == HttpStatus.SC_PROXY_AUTHENTICATION_REQUIRED) {
|
||||||
// Proxy authentication required
|
// Proxy authentication required
|
||||||
authState = (AuthState) localContext.getAttribute(ClientContext.PROXY_AUTH_STATE);
|
authState = (AuthState) localContext.getAttribute(ClientContext.PROXY_AUTH_STATE);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (authState != null) {
|
if (authState != null) {
|
||||||
System.out.println("----------------------------------------");
|
System.out.println("----------------------------------------");
|
||||||
AuthScope authScope = authState.getAuthScope();
|
AuthScope authScope = authState.getAuthScope();
|
||||||
System.out.println("Please provide credentials");
|
System.out.println("Please provide credentials");
|
||||||
System.out.println(" Host: " + authScope.getHost() + ":" + authScope.getPort());
|
System.out.println(" Host: " + authScope.getHost() + ":" + authScope.getPort());
|
||||||
System.out.println(" Realm: " + authScope.getRealm());
|
System.out.println(" Realm: " + authScope.getRealm());
|
||||||
|
|
||||||
|
|
||||||
BufferedReader console = new BufferedReader(new InputStreamReader(System.in));
|
BufferedReader console = new BufferedReader(new InputStreamReader(System.in));
|
||||||
|
|
||||||
System.out.print("Enter username: ");
|
System.out.print("Enter username: ");
|
||||||
String user = console.readLine();
|
String user = console.readLine();
|
||||||
System.out.print("Enter password: ");
|
System.out.print("Enter password: ");
|
||||||
String password = console.readLine();
|
String password = console.readLine();
|
||||||
|
|
||||||
if (user != null && user.length() > 0) {
|
if (user != null && user.length() > 0) {
|
||||||
Credentials creds = new UsernamePasswordCredentials(user, password);
|
Credentials creds = new UsernamePasswordCredentials(user, password);
|
||||||
httpclient.getCredentialsProvider().setCredentials(authScope, creds);
|
httpclient.getCredentialsProvider().setCredentials(authScope, creds);
|
||||||
@ -107,9 +107,9 @@ public static void main(String[] args) throws Exception {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// When HttpClient instance is no longer needed,
|
// When HttpClient instance is no longer needed,
|
||||||
// shut down the connection manager to ensure
|
// shut down the connection manager to ensure
|
||||||
// immediate deallocation of all system resources
|
// immediate deallocation of all system resources
|
||||||
httpclient.getConnectionManager().shutdown();
|
httpclient.getConnectionManager().shutdown();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -40,9 +40,9 @@
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* Kerberos auth example.
|
* Kerberos auth example.
|
||||||
*
|
*
|
||||||
* <p><b>Information</b></p>
|
* <p><b>Information</b></p>
|
||||||
* <p>For the best compatibility use Java >= 1.6 as it supports SPNEGO authentication more
|
* <p>For the best compatibility use Java >= 1.6 as it supports SPNEGO authentication more
|
||||||
completely.</p>
|
completely.</p>
|
||||||
* <p><em>NegotiateSchemeFactory</em> kas two custom methods</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
|
* <p><em>#setStripPort(boolean)</em> - default is false, with strip the port off the Kerberos
|
||||||
@ -92,7 +92,7 @@
|
|||||||
* </pre>
|
* </pre>
|
||||||
* <p><b>Windows specific configuration</b></p>
|
* <p><b>Windows specific configuration</b></p>
|
||||||
* <p>
|
* <p>
|
||||||
* The registry key <em>allowtgtsessionkey</em> should be added, and set correctly, to allow
|
* 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.
|
* session keys to be sent in the Kerberos Ticket-Granting Ticket.
|
||||||
* </p>
|
* </p>
|
||||||
* <p>
|
* <p>
|
||||||
@ -102,7 +102,7 @@
|
|||||||
* HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\Lsa\Kerberos\Parameters
|
* HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\Lsa\Kerberos\Parameters
|
||||||
* Value Name: allowtgtsessionkey
|
* Value Name: allowtgtsessionkey
|
||||||
* Value Type: REG_DWORD
|
* Value Type: REG_DWORD
|
||||||
* Value: 0x01
|
* Value: 0x01
|
||||||
* </pre>
|
* </pre>
|
||||||
* <p>
|
* <p>
|
||||||
* Here is the location of the registry setting on Windows XP SP2:
|
* Here is the location of the registry setting on Windows XP SP2:
|
||||||
@ -113,7 +113,7 @@
|
|||||||
* Value Type: REG_DWORD
|
* Value Type: REG_DWORD
|
||||||
* Value: 0x01
|
* Value: 0x01
|
||||||
* </pre>
|
* </pre>
|
||||||
*
|
*
|
||||||
* @since 4.1
|
* @since 4.1
|
||||||
*/
|
*/
|
||||||
public class ClientKerberosAuthentication {
|
public class ClientKerberosAuthentication {
|
||||||
@ -124,13 +124,13 @@ public static void main(String[] args) throws Exception {
|
|||||||
System.setProperty("java.security.krb5.conf", "krb5.conf");
|
System.setProperty("java.security.krb5.conf", "krb5.conf");
|
||||||
System.setProperty("sun.security.krb5.debug", "true");
|
System.setProperty("sun.security.krb5.debug", "true");
|
||||||
System.setProperty("javax.security.auth.useSubjectCredsOnly","false");
|
System.setProperty("javax.security.auth.useSubjectCredsOnly","false");
|
||||||
|
|
||||||
DefaultHttpClient httpclient = new DefaultHttpClient();
|
DefaultHttpClient httpclient = new DefaultHttpClient();
|
||||||
|
|
||||||
NegotiateSchemeFactory nsf = new NegotiateSchemeFactory();
|
NegotiateSchemeFactory nsf = new NegotiateSchemeFactory();
|
||||||
// nsf.setStripPort(false);
|
// nsf.setStripPort(false);
|
||||||
// nsf.setSpengoGenerator(new BouncySpnegoTokenGenerator());
|
// nsf.setSpengoGenerator(new BouncySpnegoTokenGenerator());
|
||||||
|
|
||||||
httpclient.getAuthSchemes().register(AuthPolicy.SPNEGO, nsf);
|
httpclient.getAuthSchemes().register(AuthPolicy.SPNEGO, nsf);
|
||||||
|
|
||||||
Credentials use_jaas_creds = new Credentials() {
|
Credentials use_jaas_creds = new Credentials() {
|
||||||
@ -142,7 +142,7 @@ public String getPassword() {
|
|||||||
public Principal getUserPrincipal() {
|
public Principal getUserPrincipal() {
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
};
|
};
|
||||||
|
|
||||||
httpclient.getCredentialsProvider().setCredentials(
|
httpclient.getCredentialsProvider().setCredentials(
|
||||||
@ -160,14 +160,14 @@ public Principal getUserPrincipal() {
|
|||||||
System.out.println(EntityUtils.toString(entity));
|
System.out.println(EntityUtils.toString(entity));
|
||||||
}
|
}
|
||||||
System.out.println("----------------------------------------");
|
System.out.println("----------------------------------------");
|
||||||
|
|
||||||
// This ensures the connection gets released back to the manager
|
// This ensures the connection gets released back to the manager
|
||||||
EntityUtils.consume(entity);
|
EntityUtils.consume(entity);
|
||||||
|
|
||||||
// When HttpClient instance is no longer needed,
|
// When HttpClient instance is no longer needed,
|
||||||
// shut down the connection manager to ensure
|
// shut down the connection manager to ensure
|
||||||
// immediate deallocation of all system resources
|
// immediate deallocation of all system resources
|
||||||
httpclient.getConnectionManager().shutdown();
|
httpclient.getConnectionManager().shutdown();
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
@ -23,7 +23,7 @@
|
|||||||
* <http://www.apache.org/>.
|
* <http://www.apache.org/>.
|
||||||
*
|
*
|
||||||
*/
|
*/
|
||||||
|
|
||||||
package org.apache.http.examples.client;
|
package org.apache.http.examples.client;
|
||||||
|
|
||||||
import org.apache.http.HttpEntity;
|
import org.apache.http.HttpEntity;
|
||||||
@ -41,24 +41,24 @@
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* An example that performs GETs from multiple threads.
|
* An example that performs GETs from multiple threads.
|
||||||
*
|
*
|
||||||
*/
|
*/
|
||||||
public class ClientMultiThreadedExecution {
|
public class ClientMultiThreadedExecution {
|
||||||
|
|
||||||
public static void main(String[] args) throws Exception {
|
public static void main(String[] args) throws Exception {
|
||||||
// Create and initialize scheme registry
|
// Create and initialize scheme registry
|
||||||
SchemeRegistry schemeRegistry = new SchemeRegistry();
|
SchemeRegistry schemeRegistry = new SchemeRegistry();
|
||||||
schemeRegistry.register(
|
schemeRegistry.register(
|
||||||
new Scheme("http", 80, PlainSocketFactory.getSocketFactory()));
|
new Scheme("http", 80, PlainSocketFactory.getSocketFactory()));
|
||||||
|
|
||||||
// Create an HttpClient with the ThreadSafeClientConnManager.
|
// Create an HttpClient with the ThreadSafeClientConnManager.
|
||||||
// This connection manager must be used if more than one thread will
|
// This connection manager must be used if more than one thread will
|
||||||
// be using the HttpClient.
|
// be using the HttpClient.
|
||||||
ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager(schemeRegistry);
|
ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager(schemeRegistry);
|
||||||
cm.setMaxTotal(100);
|
cm.setMaxTotal(100);
|
||||||
|
|
||||||
HttpClient httpClient = new DefaultHttpClient(cm);
|
HttpClient httpClient = new DefaultHttpClient(cm);
|
||||||
|
|
||||||
// create an array of URIs to perform GETs on
|
// create an array of URIs to perform GETs on
|
||||||
String[] urisToGet = {
|
String[] urisToGet = {
|
||||||
"http://hc.apache.org/",
|
"http://hc.apache.org/",
|
||||||
@ -66,60 +66,60 @@ public static void main(String[] args) throws Exception {
|
|||||||
"http://hc.apache.org/httpcomponents-client/",
|
"http://hc.apache.org/httpcomponents-client/",
|
||||||
"http://svn.apache.org/viewvc/httpcomponents/"
|
"http://svn.apache.org/viewvc/httpcomponents/"
|
||||||
};
|
};
|
||||||
|
|
||||||
// create a thread for each URI
|
// create a thread for each URI
|
||||||
GetThread[] threads = new GetThread[urisToGet.length];
|
GetThread[] threads = new GetThread[urisToGet.length];
|
||||||
for (int i = 0; i < threads.length; i++) {
|
for (int i = 0; i < threads.length; i++) {
|
||||||
HttpGet httpget = new HttpGet(urisToGet[i]);
|
HttpGet httpget = new HttpGet(urisToGet[i]);
|
||||||
threads[i] = new GetThread(httpClient, httpget, i + 1);
|
threads[i] = new GetThread(httpClient, httpget, i + 1);
|
||||||
}
|
}
|
||||||
|
|
||||||
// start the threads
|
// start the threads
|
||||||
for (int j = 0; j < threads.length; j++) {
|
for (int j = 0; j < threads.length; j++) {
|
||||||
threads[j].start();
|
threads[j].start();
|
||||||
}
|
}
|
||||||
|
|
||||||
// join the threads
|
// join the threads
|
||||||
for (int j = 0; j < threads.length; j++) {
|
for (int j = 0; j < threads.length; j++) {
|
||||||
threads[j].join();
|
threads[j].join();
|
||||||
}
|
}
|
||||||
|
|
||||||
// When HttpClient instance is no longer needed,
|
// When HttpClient instance is no longer needed,
|
||||||
// shut down the connection manager to ensure
|
// shut down the connection manager to ensure
|
||||||
// immediate deallocation of all system resources
|
// immediate deallocation of all system resources
|
||||||
httpClient.getConnectionManager().shutdown();
|
httpClient.getConnectionManager().shutdown();
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* A thread that performs a GET.
|
* A thread that performs a GET.
|
||||||
*/
|
*/
|
||||||
static class GetThread extends Thread {
|
static class GetThread extends Thread {
|
||||||
|
|
||||||
private final HttpClient httpClient;
|
private final HttpClient httpClient;
|
||||||
private final HttpContext context;
|
private final HttpContext context;
|
||||||
private final HttpGet httpget;
|
private final HttpGet httpget;
|
||||||
private final int id;
|
private final int id;
|
||||||
|
|
||||||
public GetThread(HttpClient httpClient, HttpGet httpget, int id) {
|
public GetThread(HttpClient httpClient, HttpGet httpget, int id) {
|
||||||
this.httpClient = httpClient;
|
this.httpClient = httpClient;
|
||||||
this.context = new BasicHttpContext();
|
this.context = new BasicHttpContext();
|
||||||
this.httpget = httpget;
|
this.httpget = httpget;
|
||||||
this.id = id;
|
this.id = id;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Executes the GetMethod and prints some status information.
|
* Executes the GetMethod and prints some status information.
|
||||||
*/
|
*/
|
||||||
@Override
|
@Override
|
||||||
public void run() {
|
public void run() {
|
||||||
|
|
||||||
System.out.println(id + " - about to get something from " + httpget.getURI());
|
System.out.println(id + " - about to get something from " + httpget.getURI());
|
||||||
|
|
||||||
try {
|
try {
|
||||||
|
|
||||||
// execute the method
|
// execute the method
|
||||||
HttpResponse response = httpClient.execute(httpget, context);
|
HttpResponse response = httpClient.execute(httpget, context);
|
||||||
|
|
||||||
System.out.println(id + " - get executed");
|
System.out.println(id + " - get executed");
|
||||||
// get the response body as an array of bytes
|
// get the response body as an array of bytes
|
||||||
HttpEntity entity = response.getEntity();
|
HttpEntity entity = response.getEntity();
|
||||||
@ -127,13 +127,13 @@ public void run() {
|
|||||||
byte[] bytes = EntityUtils.toByteArray(entity);
|
byte[] bytes = EntityUtils.toByteArray(entity);
|
||||||
System.out.println(id + " - " + bytes.length + " bytes read");
|
System.out.println(id + " - " + bytes.length + " bytes read");
|
||||||
}
|
}
|
||||||
|
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
httpget.abort();
|
httpget.abort();
|
||||||
System.out.println(id + " - error: " + e);
|
System.out.println(id + " - error: " + e);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
@ -40,7 +40,7 @@
|
|||||||
import org.apache.http.util.EntityUtils;
|
import org.apache.http.util.EntityUtils;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* An example of HttpClient can be customized to authenticate
|
* An example of HttpClient can be customized to authenticate
|
||||||
* preemptively using BASIC scheme.
|
* preemptively using BASIC scheme.
|
||||||
* <b/>
|
* <b/>
|
||||||
* Generally, preemptive authentication can be considered less
|
* Generally, preemptive authentication can be considered less
|
||||||
@ -51,30 +51,30 @@ public class ClientPreemptiveBasicAuthentication {
|
|||||||
|
|
||||||
public static void main(String[] args) throws Exception {
|
public static void main(String[] args) throws Exception {
|
||||||
|
|
||||||
HttpHost targetHost = new HttpHost("localhost", 80, "http");
|
HttpHost targetHost = new HttpHost("localhost", 80, "http");
|
||||||
|
|
||||||
DefaultHttpClient httpclient = new DefaultHttpClient();
|
DefaultHttpClient httpclient = new DefaultHttpClient();
|
||||||
|
|
||||||
httpclient.getCredentialsProvider().setCredentials(
|
httpclient.getCredentialsProvider().setCredentials(
|
||||||
new AuthScope(targetHost.getHostName(), targetHost.getPort()),
|
new AuthScope(targetHost.getHostName(), targetHost.getPort()),
|
||||||
new UsernamePasswordCredentials("username", "password"));
|
new UsernamePasswordCredentials("username", "password"));
|
||||||
|
|
||||||
// Create AuthCache instance
|
// Create AuthCache instance
|
||||||
AuthCache authCache = new BasicAuthCache();
|
AuthCache authCache = new BasicAuthCache();
|
||||||
// Generate BASIC scheme object and add it to the local
|
// Generate BASIC scheme object and add it to the local
|
||||||
// auth cache
|
// auth cache
|
||||||
BasicScheme basicAuth = new BasicScheme();
|
BasicScheme basicAuth = new BasicScheme();
|
||||||
authCache.put(targetHost, basicAuth);
|
authCache.put(targetHost, basicAuth);
|
||||||
|
|
||||||
// Add AuthCache to the execution context
|
// Add AuthCache to the execution context
|
||||||
BasicHttpContext localcontext = new BasicHttpContext();
|
BasicHttpContext localcontext = new BasicHttpContext();
|
||||||
localcontext.setAttribute(ClientContext.AUTH_CACHE, authCache);
|
localcontext.setAttribute(ClientContext.AUTH_CACHE, authCache);
|
||||||
|
|
||||||
HttpGet httpget = new HttpGet("/");
|
HttpGet httpget = new HttpGet("/");
|
||||||
|
|
||||||
System.out.println("executing request: " + httpget.getRequestLine());
|
System.out.println("executing request: " + httpget.getRequestLine());
|
||||||
System.out.println("to target: " + targetHost);
|
System.out.println("to target: " + targetHost);
|
||||||
|
|
||||||
for (int i = 0; i < 3; i++) {
|
for (int i = 0; i < 3; i++) {
|
||||||
HttpResponse response = httpclient.execute(targetHost, httpget, localcontext);
|
HttpResponse response = httpclient.execute(targetHost, httpget, localcontext);
|
||||||
HttpEntity entity = response.getEntity();
|
HttpEntity entity = response.getEntity();
|
||||||
@ -86,11 +86,11 @@ public static void main(String[] args) throws Exception {
|
|||||||
}
|
}
|
||||||
EntityUtils.consume(entity);
|
EntityUtils.consume(entity);
|
||||||
}
|
}
|
||||||
|
|
||||||
// When HttpClient instance is no longer needed,
|
// When HttpClient instance is no longer needed,
|
||||||
// shut down the connection manager to ensure
|
// shut down the connection manager to ensure
|
||||||
// immediate deallocation of all system resources
|
// immediate deallocation of all system resources
|
||||||
httpclient.getConnectionManager().shutdown();
|
httpclient.getConnectionManager().shutdown();
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
@ -40,7 +40,7 @@
|
|||||||
import org.apache.http.util.EntityUtils;
|
import org.apache.http.util.EntityUtils;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* An example of HttpClient can be customized to authenticate
|
* An example of HttpClient can be customized to authenticate
|
||||||
* preemptively using DIGEST scheme.
|
* preemptively using DIGEST scheme.
|
||||||
* <b/>
|
* <b/>
|
||||||
* Generally, preemptive authentication can be considered less
|
* Generally, preemptive authentication can be considered less
|
||||||
@ -51,34 +51,34 @@ public class ClientPreemptiveDigestAuthentication {
|
|||||||
|
|
||||||
public static void main(String[] args) throws Exception {
|
public static void main(String[] args) throws Exception {
|
||||||
|
|
||||||
HttpHost targetHost = new HttpHost("localhost", 80, "http");
|
HttpHost targetHost = new HttpHost("localhost", 80, "http");
|
||||||
|
|
||||||
DefaultHttpClient httpclient = new DefaultHttpClient();
|
DefaultHttpClient httpclient = new DefaultHttpClient();
|
||||||
|
|
||||||
httpclient.getCredentialsProvider().setCredentials(
|
httpclient.getCredentialsProvider().setCredentials(
|
||||||
new AuthScope(targetHost.getHostName(), targetHost.getPort()),
|
new AuthScope(targetHost.getHostName(), targetHost.getPort()),
|
||||||
new UsernamePasswordCredentials("username", "password"));
|
new UsernamePasswordCredentials("username", "password"));
|
||||||
|
|
||||||
// Create AuthCache instance
|
// Create AuthCache instance
|
||||||
AuthCache authCache = new BasicAuthCache();
|
AuthCache authCache = new BasicAuthCache();
|
||||||
// Generate DIGEST scheme object, initialize it and add it to the local
|
// Generate DIGEST scheme object, initialize it and add it to the local
|
||||||
// auth cache
|
// auth cache
|
||||||
DigestScheme digestAuth = new DigestScheme();
|
DigestScheme digestAuth = new DigestScheme();
|
||||||
// Suppose we already know the realm name
|
// Suppose we already know the realm name
|
||||||
digestAuth.overrideParamter("realm", "some realm");
|
digestAuth.overrideParamter("realm", "some realm");
|
||||||
// Suppose we already know the expected nonce value
|
// Suppose we already know the expected nonce value
|
||||||
digestAuth.overrideParamter("nonce", "whatever");
|
digestAuth.overrideParamter("nonce", "whatever");
|
||||||
authCache.put(targetHost, digestAuth);
|
authCache.put(targetHost, digestAuth);
|
||||||
|
|
||||||
// Add AuthCache to the execution context
|
// Add AuthCache to the execution context
|
||||||
BasicHttpContext localcontext = new BasicHttpContext();
|
BasicHttpContext localcontext = new BasicHttpContext();
|
||||||
localcontext.setAttribute(ClientContext.AUTH_CACHE, authCache);
|
localcontext.setAttribute(ClientContext.AUTH_CACHE, authCache);
|
||||||
|
|
||||||
HttpGet httpget = new HttpGet("/");
|
HttpGet httpget = new HttpGet("/");
|
||||||
|
|
||||||
System.out.println("executing request: " + httpget.getRequestLine());
|
System.out.println("executing request: " + httpget.getRequestLine());
|
||||||
System.out.println("to target: " + targetHost);
|
System.out.println("to target: " + targetHost);
|
||||||
|
|
||||||
for (int i = 0; i < 3; i++) {
|
for (int i = 0; i < 3; i++) {
|
||||||
HttpResponse response = httpclient.execute(targetHost, httpget, localcontext);
|
HttpResponse response = httpclient.execute(targetHost, httpget, localcontext);
|
||||||
HttpEntity entity = response.getEntity();
|
HttpEntity entity = response.getEntity();
|
||||||
@ -90,11 +90,11 @@ public static void main(String[] args) throws Exception {
|
|||||||
}
|
}
|
||||||
EntityUtils.consume(entity);
|
EntityUtils.consume(entity);
|
||||||
}
|
}
|
||||||
|
|
||||||
// When HttpClient instance is no longer needed,
|
// When HttpClient instance is no longer needed,
|
||||||
// shut down the connection manager to ensure
|
// shut down the connection manager to ensure
|
||||||
// immediate deallocation of all system resources
|
// immediate deallocation of all system resources
|
||||||
httpclient.getConnectionManager().shutdown();
|
httpclient.getConnectionManager().shutdown();
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
@ -36,30 +36,30 @@
|
|||||||
import org.apache.http.util.EntityUtils;
|
import org.apache.http.util.EntityUtils;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* A simple example that uses HttpClient to execute an HTTP request
|
* A simple example that uses HttpClient to execute an HTTP request
|
||||||
* over a secure connection tunneled through an authenticating proxy.
|
* over a secure connection tunneled through an authenticating proxy.
|
||||||
*/
|
*/
|
||||||
public class ClientProxyAuthentication {
|
public class ClientProxyAuthentication {
|
||||||
|
|
||||||
public static void main(String[] args) throws Exception {
|
public static void main(String[] args) throws Exception {
|
||||||
|
|
||||||
DefaultHttpClient httpclient = new DefaultHttpClient();
|
DefaultHttpClient httpclient = new DefaultHttpClient();
|
||||||
|
|
||||||
httpclient.getCredentialsProvider().setCredentials(
|
httpclient.getCredentialsProvider().setCredentials(
|
||||||
new AuthScope("localhost", 8080),
|
new AuthScope("localhost", 8080),
|
||||||
new UsernamePasswordCredentials("username", "password"));
|
new UsernamePasswordCredentials("username", "password"));
|
||||||
|
|
||||||
HttpHost targetHost = new HttpHost("www.verisign.com", 443, "https");
|
HttpHost targetHost = new HttpHost("www.verisign.com", 443, "https");
|
||||||
HttpHost proxy = new HttpHost("localhost", 8080);
|
HttpHost proxy = new HttpHost("localhost", 8080);
|
||||||
|
|
||||||
httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
|
httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
|
||||||
|
|
||||||
HttpGet httpget = new HttpGet("/");
|
HttpGet httpget = new HttpGet("/");
|
||||||
|
|
||||||
System.out.println("executing request: " + httpget.getRequestLine());
|
System.out.println("executing request: " + httpget.getRequestLine());
|
||||||
System.out.println("via proxy: " + proxy);
|
System.out.println("via proxy: " + proxy);
|
||||||
System.out.println("to target: " + targetHost);
|
System.out.println("to target: " + targetHost);
|
||||||
|
|
||||||
HttpResponse response = httpclient.execute(targetHost, httpget);
|
HttpResponse response = httpclient.execute(targetHost, httpget);
|
||||||
HttpEntity entity = response.getEntity();
|
HttpEntity entity = response.getEntity();
|
||||||
|
|
||||||
@ -69,10 +69,10 @@ public static void main(String[] args) throws Exception {
|
|||||||
System.out.println("Response content length: " + entity.getContentLength());
|
System.out.println("Response content length: " + entity.getContentLength());
|
||||||
}
|
}
|
||||||
EntityUtils.consume(entity);
|
EntityUtils.consume(entity);
|
||||||
|
|
||||||
// When HttpClient instance is no longer needed,
|
// When HttpClient instance is no longer needed,
|
||||||
// shut down the connection manager to ensure
|
// shut down the connection manager to ensure
|
||||||
// immediate deallocation of all system resources
|
// immediate deallocation of all system resources
|
||||||
httpclient.getConnectionManager().shutdown();
|
httpclient.getConnectionManager().shutdown();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -34,16 +34,16 @@
|
|||||||
import org.apache.http.impl.client.DefaultHttpClient;
|
import org.apache.http.impl.client.DefaultHttpClient;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* This example demonstrates the use of the {@link ResponseHandler} to simplify
|
* This example demonstrates the use of the {@link ResponseHandler} to simplify
|
||||||
* the process of processing the HTTP response and releasing associated resources.
|
* the process of processing the HTTP response and releasing associated resources.
|
||||||
*/
|
*/
|
||||||
public class ClientWithResponseHandler {
|
public class ClientWithResponseHandler {
|
||||||
|
|
||||||
public final static void main(String[] args) throws Exception {
|
public final static void main(String[] args) throws Exception {
|
||||||
|
|
||||||
HttpClient httpclient = new DefaultHttpClient();
|
HttpClient httpclient = new DefaultHttpClient();
|
||||||
|
|
||||||
HttpGet httpget = new HttpGet("http://www.google.com/");
|
HttpGet httpget = new HttpGet("http://www.google.com/");
|
||||||
|
|
||||||
System.out.println("executing request " + httpget.getURI());
|
System.out.println("executing request " + httpget.getURI());
|
||||||
|
|
||||||
@ -54,11 +54,11 @@ public final static void main(String[] args) throws Exception {
|
|||||||
System.out.println(responseBody);
|
System.out.println(responseBody);
|
||||||
System.out.println("----------------------------------------");
|
System.out.println("----------------------------------------");
|
||||||
|
|
||||||
// When HttpClient instance is no longer needed,
|
// When HttpClient instance is no longer needed,
|
||||||
// shut down the connection manager to ensure
|
// shut down the connection manager to ensure
|
||||||
// immediate deallocation of all system resources
|
// immediate deallocation of all system resources
|
||||||
httpclient.getConnectionManager().shutdown();
|
httpclient.getConnectionManager().shutdown();
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -85,7 +85,7 @@ public final static void main(String[] args) throws Exception {
|
|||||||
|
|
||||||
HttpRequest req = new BasicHttpRequest("OPTIONS", "*", HttpVersion.HTTP_1_1);
|
HttpRequest req = new BasicHttpRequest("OPTIONS", "*", HttpVersion.HTTP_1_1);
|
||||||
req.addHeader("Host", target.getHostName());
|
req.addHeader("Host", target.getHostName());
|
||||||
|
|
||||||
HttpContext ctx = new BasicHttpContext();
|
HttpContext ctx = new BasicHttpContext();
|
||||||
|
|
||||||
System.out.println("preparing route to " + target);
|
System.out.println("preparing route to " + target);
|
||||||
|
@ -105,7 +105,7 @@ public final static void main(String[] args) throws Exception {
|
|||||||
String authority = target.getHostName() + ":" + target.getPort();
|
String authority = target.getHostName() + ":" + target.getPort();
|
||||||
HttpRequest connect = new BasicHttpRequest("CONNECT", authority, HttpVersion.HTTP_1_1);
|
HttpRequest connect = new BasicHttpRequest("CONNECT", authority, HttpVersion.HTTP_1_1);
|
||||||
connect.addHeader("Host", authority);
|
connect.addHeader("Host", authority);
|
||||||
|
|
||||||
System.out.println("opening tunnel to " + target);
|
System.out.println("opening tunnel to " + target);
|
||||||
conn.sendRequestHeader(connect);
|
conn.sendRequestHeader(connect);
|
||||||
// there is no request entity
|
// there is no request entity
|
||||||
|
@ -77,7 +77,7 @@ public static void main(String[] args) throws Exception {
|
|||||||
|
|
||||||
HttpRequest req = new BasicHttpRequest("OPTIONS", "*", HttpVersion.HTTP_1_1);
|
HttpRequest req = new BasicHttpRequest("OPTIONS", "*", HttpVersion.HTTP_1_1);
|
||||||
req.addHeader("Host", target.getHostName());
|
req.addHeader("Host", target.getHostName());
|
||||||
|
|
||||||
HttpContext ctx = new BasicHttpContext();
|
HttpContext ctx = new BasicHttpContext();
|
||||||
|
|
||||||
OperatedClientConnection conn = scop.createConnection();
|
OperatedClientConnection conn = scop.createConnection();
|
||||||
|
@ -67,9 +67,9 @@ public static void main(String[] args) throws Exception {
|
|||||||
// Register the "http" and "https" protocol schemes, they are
|
// Register the "http" and "https" protocol schemes, they are
|
||||||
// required by the default operator to look up socket factories.
|
// required by the default operator to look up socket factories.
|
||||||
SchemeRegistry supportedSchemes = new SchemeRegistry();
|
SchemeRegistry supportedSchemes = new SchemeRegistry();
|
||||||
supportedSchemes.register(new Scheme("http",
|
supportedSchemes.register(new Scheme("http",
|
||||||
80, PlainSocketFactory.getSocketFactory()));
|
80, PlainSocketFactory.getSocketFactory()));
|
||||||
supportedSchemes.register(new Scheme("https",
|
supportedSchemes.register(new Scheme("https",
|
||||||
443, SSLSocketFactory.getSocketFactory()));
|
443, SSLSocketFactory.getSocketFactory()));
|
||||||
|
|
||||||
// Prepare parameters.
|
// Prepare parameters.
|
||||||
@ -86,7 +86,7 @@ public static void main(String[] args) throws Exception {
|
|||||||
// In a real application, request interceptors should be used
|
// In a real application, request interceptors should be used
|
||||||
// to add the required headers.
|
// to add the required headers.
|
||||||
req.addHeader("Host", target.getHostName());
|
req.addHeader("Host", target.getHostName());
|
||||||
|
|
||||||
HttpContext ctx = new BasicHttpContext();
|
HttpContext ctx = new BasicHttpContext();
|
||||||
|
|
||||||
OperatedClientConnection conn = scop.createConnection();
|
OperatedClientConnection conn = scop.createConnection();
|
||||||
@ -97,7 +97,7 @@ public static void main(String[] args) throws Exception {
|
|||||||
// Creates a request to tunnel a connection.
|
// Creates a request to tunnel a connection.
|
||||||
// For details see RFC 2817, section 5.2
|
// For details see RFC 2817, section 5.2
|
||||||
String authority = target.getHostName() + ":" + target.getPort();
|
String authority = target.getHostName() + ":" + target.getPort();
|
||||||
HttpRequest connect = new BasicHttpRequest("CONNECT", authority,
|
HttpRequest connect = new BasicHttpRequest("CONNECT", authority,
|
||||||
HttpVersion.HTTP_1_1);
|
HttpVersion.HTTP_1_1);
|
||||||
// In a real application, request interceptors should be used
|
// In a real application, request interceptors should be used
|
||||||
// to add the required headers.
|
// to add the required headers.
|
||||||
|
Loading…
x
Reference in New Issue
Block a user