Updated HttpClient examples

git-svn-id: https://svn.apache.org/repos/asf/httpcomponents/httpclient/trunk@1529450 13f79535-47bb-0310-9956-ffa450edef68
This commit is contained in:
Oleg Kalnichevski 2013-10-05 13:24:29 +00:00
parent 922d442ce9
commit d6ffa5362c
17 changed files with 85 additions and 422 deletions

View File

@ -27,7 +27,6 @@
package org.apache.http.examples.client; package org.apache.http.examples.client;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.CloseableHttpClient;
@ -43,18 +42,11 @@ public class ClientAbortMethod {
try { try {
HttpGet httpget = new HttpGet("http://www.apache.org/"); HttpGet httpget = new HttpGet("http://www.apache.org/");
System.out.println("executing request " + httpget.getURI()); System.out.println("Executing request " + httpget.getURI());
CloseableHttpResponse response = httpclient.execute(httpget); CloseableHttpResponse response = httpclient.execute(httpget);
try { try {
HttpEntity entity = response.getEntity();
System.out.println("----------------------------------------"); System.out.println("----------------------------------------");
System.out.println(response.getStatusLine()); System.out.println(response.getStatusLine());
if (entity != null) {
System.out.println("Response content length: " + entity.getContentLength());
}
System.out.println("----------------------------------------");
// 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();

View File

@ -26,7 +26,6 @@
*/ */
package org.apache.http.examples.client; package org.apache.http.examples.client;
import org.apache.http.HttpEntity;
import org.apache.http.auth.AuthScope; import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials; import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider; import org.apache.http.client.CredentialsProvider;
@ -49,21 +48,17 @@ public class ClientAuthentication {
new AuthScope("localhost", 443), new AuthScope("localhost", 443),
new UsernamePasswordCredentials("username", "password")); new UsernamePasswordCredentials("username", "password"));
CloseableHttpClient httpclient = HttpClients.custom() CloseableHttpClient httpclient = HttpClients.custom()
.setDefaultCredentialsProvider(credsProvider).build(); .setDefaultCredentialsProvider(credsProvider)
.build();
try { try {
HttpGet httpget = new HttpGet("https://localhost/protected"); HttpGet httpget = new HttpGet("http://localhost/");
System.out.println("executing request" + httpget.getRequestLine()); System.out.println("Executing request " + httpget.getRequestLine());
CloseableHttpResponse response = httpclient.execute(httpget); CloseableHttpResponse response = httpclient.execute(httpget);
try { try {
HttpEntity entity = response.getEntity();
System.out.println("----------------------------------------"); System.out.println("----------------------------------------");
System.out.println(response.getStatusLine()); System.out.println(response.getStatusLine());
if (entity != null) { EntityUtils.consume(response.getEntity());
System.out.println("Response content length: " + entity.getContentLength());
}
EntityUtils.consume(entity);
} finally { } finally {
response.close(); response.close();
} }

View File

@ -29,9 +29,9 @@ package org.apache.http.examples.client;
import java.io.File; import java.io.File;
import java.io.FileInputStream; import java.io.FileInputStream;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost; import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.InputStreamEntity; import org.apache.http.entity.InputStreamEntity;
import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients; import org.apache.http.impl.client.HttpClients;
@ -49,14 +49,12 @@ public class ClientChunkEncodedPost {
} }
CloseableHttpClient httpclient = HttpClients.createDefault(); CloseableHttpClient httpclient = HttpClients.createDefault();
try { try {
HttpPost httppost = new HttpPost("http://localhost:8080" + HttpPost httppost = new HttpPost("http://localhost/");
"/servlets-examples/servlet/RequestInfoExample");
File file = new File(args[0]); File file = new File(args[0]);
InputStreamEntity reqEntity = new InputStreamEntity( InputStreamEntity reqEntity = new InputStreamEntity(
new FileInputStream(file), -1); new FileInputStream(file), -1, ContentType.APPLICATION_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
@ -66,18 +64,12 @@ public class ClientChunkEncodedPost {
httppost.setEntity(reqEntity); httppost.setEntity(reqEntity);
System.out.println("executing request " + httppost.getRequestLine()); System.out.println("Executing request: " + httppost.getRequestLine());
CloseableHttpResponse response = httpclient.execute(httppost); CloseableHttpResponse response = httpclient.execute(httppost);
try { try {
HttpEntity resEntity = response.getEntity();
System.out.println("----------------------------------------"); System.out.println("----------------------------------------");
System.out.println(response.getStatusLine()); System.out.println(response.getStatusLine());
if (resEntity != null) { EntityUtils.consume(response.getEntity());
System.out.println("Response content length: " + resEntity.getContentLength());
System.out.println("Chunked?: " + resEntity.isChunked());
}
EntityUtils.consume(resEntity);
} finally { } finally {
response.close(); response.close();
} }

View File

@ -45,15 +45,13 @@ public class ClientConnectionRelease {
public final static void main(String[] args) throws Exception { public final static void main(String[] args) throws Exception {
CloseableHttpClient httpclient = HttpClients.createDefault(); CloseableHttpClient httpclient = HttpClients.createDefault();
try { try {
HttpGet httpget = new HttpGet("http://www.apache.org/"); HttpGet httpget = new HttpGet("http://localhost/");
// Execute HTTP request System.out.println("Executing request " + httpget.getRequestLine());
System.out.println("executing request " + httpget.getURI());
CloseableHttpResponse response = httpclient.execute(httpget); CloseableHttpResponse response = httpclient.execute(httpget);
try { try {
System.out.println("----------------------------------------"); System.out.println("----------------------------------------");
System.out.println(response.getStatusLine()); System.out.println(response.getStatusLine());
System.out.println("----------------------------------------");
// Get hold of the response entity // Get hold of the response entity
HttpEntity entity = response.getEntity(); HttpEntity entity = response.getEntity();

View File

@ -29,7 +29,6 @@ package org.apache.http.examples.client;
import java.util.List; import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.client.CookieStore; import org.apache.http.client.CookieStore;
import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpGet;
@ -57,29 +56,19 @@ public class ClientCustomContext {
// Bind custom cookie store to the local context // Bind custom cookie store to the local context
localContext.setCookieStore(cookieStore); localContext.setCookieStore(cookieStore);
HttpGet httpget = new HttpGet("http://www.google.com/"); HttpGet httpget = new HttpGet("http://localhost/");
System.out.println("Executing request " + httpget.getRequestLine());
System.out.println("executing request " + httpget.getURI());
// Pass local context as a parameter // Pass local context as a parameter
CloseableHttpResponse response = httpclient.execute(httpget, localContext); CloseableHttpResponse response = httpclient.execute(httpget, localContext);
try { try {
HttpEntity entity = response.getEntity();
System.out.println("----------------------------------------"); System.out.println("----------------------------------------");
System.out.println(response.getStatusLine()); System.out.println(response.getStatusLine());
if (entity != null) {
System.out.println("Response content length: " + entity.getContentLength());
}
List<Cookie> cookies = cookieStore.getCookies(); List<Cookie> cookies = cookieStore.getCookies();
for (int i = 0; i < cookies.size(); i++) { for (int i = 0; i < cookies.size(); i++) {
System.out.println("Local cookie: " + cookies.get(i)); System.out.println("Local cookie: " + cookies.get(i));
} }
EntityUtils.consume(response.getEntity());
// Consume response content
EntityUtils.consume(entity);
System.out.println("----------------------------------------");
} finally { } finally {
response.close(); response.close();
} }

View File

@ -37,6 +37,7 @@ import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.ssl.SSLContexts; import org.apache.http.conn.ssl.SSLContexts;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory; import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.TrustSelfSignedStrategy;
import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients; import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils; import org.apache.http.util.EntityUtils;
@ -55,11 +56,16 @@ public class ClientCustomSSL {
} finally { } finally {
instream.close(); instream.close();
} }
SSLContext sslcontext = SSLContexts.custom()
.loadTrustMaterial(trustStore)
.build();
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext, // Trust own CA and all self-signed certs
SSLContext sslcontext = SSLContexts.custom()
.loadTrustMaterial(trustStore, new TrustSelfSignedStrategy())
.build();
// Allow TLSv1 protocol only
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
sslcontext,
new String[] { "TLSv1" },
null,
SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER); SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
CloseableHttpClient httpclient = HttpClients.custom() CloseableHttpClient httpclient = HttpClients.custom()
.setSSLSocketFactory(sslsf) .setSSLSocketFactory(sslsf)

View File

@ -28,7 +28,6 @@ package org.apache.http.examples.client;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.HttpClientConnectionManager; import org.apache.http.conn.HttpClientConnectionManager;
@ -47,14 +46,14 @@ public class ClientEvictExpiredConnections {
PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(); PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
cm.setMaxTotal(100); cm.setMaxTotal(100);
CloseableHttpClient httpclient = HttpClients.custom() CloseableHttpClient httpclient = HttpClients.custom()
.setConnectionManager(cm).build(); .setConnectionManager(cm)
.build();
try { try {
// create an array of URIs to perform GETs on // create an array of URIs to perform GETs on
String[] urisToGet = { String[] urisToGet = {
"http://jakarta.apache.org/", "http://hc.apache.org/",
"http://jakarta.apache.org/commons/", "http://hc.apache.org/httpcomponents-core-ga/",
"http://jakarta.apache.org/commons/httpclient/", "http://hc.apache.org/httpcomponents-client-ga/",
"http://svn.apache.org/viewvc/jakarta/httpcomponents/"
}; };
IdleConnectionEvictor connEvictor = new IdleConnectionEvictor(cm); IdleConnectionEvictor connEvictor = new IdleConnectionEvictor(cm);
@ -64,20 +63,13 @@ public class ClientEvictExpiredConnections {
String requestURI = urisToGet[i]; String requestURI = urisToGet[i];
HttpGet request = new HttpGet(requestURI); HttpGet request = new HttpGet(requestURI);
System.out.println("executing request " + requestURI); System.out.println("Executing request " + requestURI);
CloseableHttpResponse response = httpclient.execute(request); CloseableHttpResponse response = httpclient.execute(request);
try { try {
HttpEntity entity = response.getEntity();
System.out.println("----------------------------------------"); System.out.println("----------------------------------------");
System.out.println(response.getStatusLine()); System.out.println(response.getStatusLine());
if (entity != null) { EntityUtils.consume(response.getEntity());
System.out.println("Response content length: " + entity.getContentLength());
}
System.out.println("----------------------------------------");
EntityUtils.consume(entity);
} finally { } finally {
response.close(); response.close();
} }

View File

@ -27,8 +27,6 @@
package org.apache.http.examples.client; 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.HttpHost;
import org.apache.http.client.config.RequestConfig; import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.CloseableHttpResponse;
@ -47,29 +45,22 @@ public class ClientExecuteProxy {
public static void main(String[] args)throws Exception { public static void main(String[] args)throws Exception {
CloseableHttpClient httpclient = HttpClients.createDefault(); CloseableHttpClient httpclient = HttpClients.createDefault();
try { try {
HttpHost target = new HttpHost("issues.apache.org", 443, "https"); HttpHost target = new HttpHost("localhost", 443, "https");
HttpHost proxy = new HttpHost("127.0.0.1", 8080, "http"); HttpHost proxy = new HttpHost("127.0.0.1", 8080, "http");
RequestConfig config = RequestConfig.custom().setProxy(proxy).build(); RequestConfig config = RequestConfig.custom()
.setProxy(proxy)
.build();
HttpGet request = new HttpGet("/"); HttpGet request = new HttpGet("/");
request.setConfig(config); request.setConfig(config);
System.out.println("executing request to " + target + " via " + proxy); System.out.println("Executing request " + request.getRequestLine() + " to " + target + " via " + proxy);
CloseableHttpResponse response = httpclient.execute(target, request); CloseableHttpResponse response = httpclient.execute(target, request);
try { try {
HttpEntity entity = response.getEntity();
System.out.println("----------------------------------------"); System.out.println("----------------------------------------");
System.out.println(response.getStatusLine()); System.out.println(response.getStatusLine());
Header[] headers = response.getAllHeaders(); EntityUtils.consume(response.getEntity());
for (int i = 0; i<headers.length; i++) {
System.out.println(headers[i]);
}
System.out.println("----------------------------------------");
if (entity != null) {
System.out.println(EntityUtils.toString(entity));
}
} finally { } finally {
response.close(); response.close();
} }

View File

@ -33,8 +33,6 @@ import java.net.Proxy;
import java.net.Socket; import java.net.Socket;
import java.net.SocketTimeoutException; import java.net.SocketTimeoutException;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHost; import org.apache.http.HttpHost;
import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpGet;
@ -58,34 +56,26 @@ public class ClientExecuteSOCKS {
public static void main(String[] args)throws Exception { public static void main(String[] args)throws Exception {
Registry<ConnectionSocketFactory> reg = RegistryBuilder.<ConnectionSocketFactory>create() Registry<ConnectionSocketFactory> reg = RegistryBuilder.<ConnectionSocketFactory>create()
.register("http", new MyConnectionSocketFactory()) .register("http", new MyConnectionSocketFactory())
.build(); .build();
PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(reg); PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(reg);
CloseableHttpClient httpclient = HttpClients.custom().setConnectionManager(cm).build(); CloseableHttpClient httpclient = HttpClients.custom()
.setConnectionManager(cm)
.build();
try { try {
InetSocketAddress socksaddr = new InetSocketAddress("mysockshost", 1234); InetSocketAddress socksaddr = new InetSocketAddress("mysockshost", 1234);
HttpClientContext context = HttpClientContext.create(); HttpClientContext context = HttpClientContext.create();
context.setAttribute("socks.address", socksaddr); context.setAttribute("socks.address", socksaddr);
HttpHost target = new HttpHost("www.apache.org", 80, "http"); HttpHost target = new HttpHost("localhost", 80, "http");
HttpGet request = new HttpGet("/"); HttpGet request = new HttpGet("/");
System.out.println("executing request to " + target + " via SOCKS proxy " + socksaddr); System.out.println("Executing request " + request + " to " + target + " via SOCKS proxy " + socksaddr);
CloseableHttpResponse response = httpclient.execute(target, request); CloseableHttpResponse response = httpclient.execute(target, request);
try { try {
HttpEntity entity = response.getEntity();
System.out.println("----------------------------------------"); System.out.println("----------------------------------------");
System.out.println(response.getStatusLine()); System.out.println(response.getStatusLine());
Header[] headers = response.getAllHeaders(); EntityUtils.consume(response.getEntity());
for (int i = 0; i<headers.length; i++) {
System.out.println(headers[i]);
}
System.out.println("----------------------------------------");
if (entity != null) {
System.out.println(EntityUtils.toString(entity));
}
} finally { } finally {
response.close(); response.close();
} }
@ -121,8 +111,7 @@ public class ClientExecuteSOCKS {
try { try {
sock.connect(remoteAddress, connectTimeout); sock.connect(remoteAddress, connectTimeout);
} catch (SocketTimeoutException ex) { } catch (SocketTimeoutException ex) {
throw new ConnectTimeoutException("Connect to " + remoteAddress.getHostName() + "/" throw new ConnectTimeoutException(ex, host, remoteAddress.getAddress());
+ remoteAddress.getAddress() + " timed out");
} }
return sock; return sock;
} }

View File

@ -26,21 +26,18 @@
*/ */
package org.apache.http.examples.client; package org.apache.http.examples.client;
import java.util.ArrayList; import java.net.URI;
import java.util.List; import java.util.List;
import org.apache.http.Consts;
import org.apache.http.HttpEntity; import org.apache.http.HttpEntity;
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.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost; import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.client.methods.RequestBuilder;
import org.apache.http.cookie.Cookie; import org.apache.http.cookie.Cookie;
import org.apache.http.impl.client.BasicCookieStore; import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients; import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils; import org.apache.http.util.EntityUtils;
/** /**
@ -51,10 +48,11 @@ public class ClientFormLogin {
public static void main(String[] args) throws Exception { public static void main(String[] args) throws Exception {
BasicCookieStore cookieStore = new BasicCookieStore(); BasicCookieStore cookieStore = new BasicCookieStore();
CloseableHttpClient httpclient = HttpClients.custom().setDefaultCookieStore(cookieStore).build(); CloseableHttpClient httpclient = HttpClients.custom()
.setDefaultCookieStore(cookieStore)
.build();
try { try {
HttpGet httpget = new HttpGet("https://portal.sun.com/portal/dt"); HttpGet httpget = new HttpGet("https://someportal/");
CloseableHttpResponse response1 = httpclient.execute(httpget); CloseableHttpResponse response1 = httpclient.execute(httpget);
try { try {
HttpEntity entity = response1.getEntity(); HttpEntity entity = response1.getEntity();
@ -75,17 +73,12 @@ public class ClientFormLogin {
response1.close(); response1.close();
} }
HttpPost httpost = new HttpPost("https://portal.sun.com/amserver/UI/Login?" + HttpUriRequest login = RequestBuilder.post()
"org=self_registered_users&" + .setUri(new URI("https://someportal/"))
"goto=/portal/dt&" + .addParameter("IDToken1", "username")
"gotoOnFail=/portal/dt?error=true"); .addParameter("IDToken2", "password")
List <NameValuePair> nvps = new ArrayList <NameValuePair>(); .build();
nvps.add(new BasicNameValuePair("IDToken1", "username")); CloseableHttpResponse response2 = httpclient.execute(login);
nvps.add(new BasicNameValuePair("IDToken2", "password"));
httpost.setEntity(new UrlEncodedFormEntity(nvps, Consts.UTF_8));
CloseableHttpResponse response2 = httpclient.execute(httpost);
try { try {
HttpEntity entity = response2.getEntity(); HttpEntity entity = response2.getEntity();

View File

@ -1,126 +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.io.IOException;
import org.apache.http.Header;
import org.apache.http.HeaderElement;
import org.apache.http.HttpEntity;
import org.apache.http.HttpException;
import org.apache.http.HttpRequest;
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.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.protocol.HttpContext;
import org.apache.http.util.EntityUtils;
/**
* Demonstration of the use of protocol interceptors to transparently
* modify properties of HTTP messages sent / received by the HTTP client.
* <p/>
* In this particular case HTTP client is made capable of transparent content
* GZIP compression by adding two protocol interceptors: a request interceptor
* that adds 'Accept-Encoding: gzip' header to all outgoing requests and
* a response interceptor that automatically expands compressed response
* entities by wrapping them with a uncompressing decorator class. The use of
* protocol interceptors makes content compression completely transparent to
* the consumer of the {@link org.apache.http.client.HttpClient HttpClient}
* interface.
*/
public class ClientGZipContentCompression {
public final static void main(String[] args) throws Exception {
CloseableHttpClient httpclient = HttpClients.custom()
.addInterceptorFirst(new HttpRequestInterceptor() {
public void process(
final HttpRequest request,
final HttpContext context) throws HttpException, IOException {
if (!request.containsHeader("Accept-Encoding")) {
request.addHeader("Accept-Encoding", "gzip");
}
}}).addInterceptorFirst(new HttpResponseInterceptor() {
public void process(
final HttpResponse response,
final HttpContext context) throws HttpException, IOException {
HttpEntity entity = response.getEntity();
if (entity != null) {
Header ceheader = entity.getContentEncoding();
if (ceheader != null) {
HeaderElement[] codecs = ceheader.getElements();
for (int i = 0; i < codecs.length; i++) {
if (codecs[i].getName().equalsIgnoreCase("gzip")) {
response.setEntity(
new GzipDecompressingEntity(response.getEntity()));
return;
}
}
}
}
}
}).build();
try {
HttpGet httpget = new HttpGet("http://www.apache.org/");
// Execute HTTP request
System.out.println("executing request " + httpget.getURI());
CloseableHttpResponse response = httpclient.execute(httpget);
try {
System.out.println("----------------------------------------");
System.out.println(response.getStatusLine());
System.out.println(response.getLastHeader("Content-Encoding"));
System.out.println(response.getLastHeader("Content-Length"));
System.out.println("----------------------------------------");
HttpEntity entity = response.getEntity();
if (entity != null) {
String content = EntityUtils.toString(entity);
System.out.println(content);
System.out.println("----------------------------------------");
System.out.println("Uncompressed size: "+content.length());
}
} finally {
response.close();
}
} finally {
httpclient.close();
}
}
}

View File

@ -1,124 +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.io.BufferedReader;
import java.io.InputStreamReader;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
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.HttpClientContext;
import org.apache.http.conn.routing.RouteInfo;
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;
/**
* A simple example that uses HttpClient to execute an HTTP request against
* a target site that requires user authentication.
*/
public class ClientInteractiveAuthentication {
public static void main(String[] args) throws Exception {
BasicCredentialsProvider credsProvider = new BasicCredentialsProvider();
CloseableHttpClient httpclient = HttpClients.custom()
.setDefaultCredentialsProvider(credsProvider).build();
try {
// Create local execution context
HttpClientContext localContext = HttpClientContext.create();
HttpGet httpget = new HttpGet("http://localhost/test");
boolean trying = true;
while (trying) {
System.out.println("executing request " + httpget.getRequestLine());
CloseableHttpResponse response = httpclient.execute(httpget, localContext);
try {
System.out.println("----------------------------------------");
System.out.println(response.getStatusLine());
// Consume response content
HttpEntity entity = response.getEntity();
EntityUtils.consume(entity);
int sc = response.getStatusLine().getStatusCode();
RouteInfo route = localContext.getHttpRoute();
AuthState authState = null;
HttpHost authhost = null;
if (sc == HttpStatus.SC_UNAUTHORIZED) {
// Target host authentication required
authState = localContext.getTargetAuthState();
authhost = route.getTargetHost();
}
if (sc == HttpStatus.SC_PROXY_AUTHENTICATION_REQUIRED) {
// Proxy authentication required
authState = localContext.getProxyAuthState();
authhost = route.getProxyHost();
}
if (authState != null) {
System.out.println("----------------------------------------");
AuthScheme authscheme = authState.getAuthScheme();
System.out.println("Please provide credentials for " +
authscheme.getRealm() + "@" + authhost.toHostString());
BufferedReader console = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter username: ");
String user = console.readLine();
System.out.print("Enter password: ");
String password = console.readLine();
if (user != null && user.length() > 0) {
Credentials creds = new UsernamePasswordCredentials(user, password);
credsProvider.setCredentials(new AuthScope(authhost), creds);
trying = true;
} else {
trying = false;
}
} else {
trying = false;
}
} finally {
response.close();
}
}
} finally {
httpclient.close();
}
}
}

View File

@ -49,14 +49,15 @@ public class ClientMultiThreadedExecution {
PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(); PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
cm.setMaxTotal(100); cm.setMaxTotal(100);
CloseableHttpClient httpclient = HttpClients.custom().setConnectionManager(cm).build(); CloseableHttpClient httpclient = HttpClients.custom()
.setConnectionManager(cm)
.build();
try { try {
// create an array of URIs to perform GETs on // create an array of URIs to perform GETs on
String[] urisToGet = { String[] urisToGet = {
"http://hc.apache.org/", "http://hc.apache.org/",
"http://hc.apache.org/httpcomponents-core-ga/", "http://hc.apache.org/httpcomponents-core-ga/",
"http://hc.apache.org/httpcomponents-client-ga/", "http://hc.apache.org/httpcomponents-client-ga/",
"http://svn.apache.org/viewvc/httpcomponents/"
}; };
// create a thread for each URI // create a thread for each URI

View File

@ -26,7 +26,6 @@
*/ */
package org.apache.http.examples.client; package org.apache.http.examples.client;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHost; import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope; import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials; import org.apache.http.auth.UsernamePasswordCredentials;
@ -53,10 +52,10 @@ import org.apache.http.util.EntityUtils;
public class ClientPreemptiveBasicAuthentication { public class ClientPreemptiveBasicAuthentication {
public static void main(String[] args) throws Exception { public static void main(String[] args) throws Exception {
HttpHost targetHost = new HttpHost("localhost", 80, "http"); HttpHost target = new HttpHost("localhost", 80, "http");
CredentialsProvider credsProvider = new BasicCredentialsProvider(); CredentialsProvider credsProvider = new BasicCredentialsProvider();
credsProvider.setCredentials( credsProvider.setCredentials(
new AuthScope(targetHost.getHostName(), targetHost.getPort()), new AuthScope(target.getHostName(), target.getPort()),
new UsernamePasswordCredentials("username", "password")); new UsernamePasswordCredentials("username", "password"));
CloseableHttpClient httpclient = HttpClients.custom() CloseableHttpClient httpclient = HttpClients.custom()
.setDefaultCredentialsProvider(credsProvider).build(); .setDefaultCredentialsProvider(credsProvider).build();
@ -67,7 +66,7 @@ public class ClientPreemptiveBasicAuthentication {
// 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(target, basicAuth);
// Add AuthCache to the execution context // Add AuthCache to the execution context
HttpClientContext localContext = HttpClientContext.create(); HttpClientContext localContext = HttpClientContext.create();
@ -75,20 +74,13 @@ public class ClientPreemptiveBasicAuthentication {
HttpGet httpget = new HttpGet("/"); HttpGet httpget = new HttpGet("/");
System.out.println("executing request: " + httpget.getRequestLine()); System.out.println("Executing request " + httpget.getRequestLine() + " to target " + target);
System.out.println("to target: " + targetHost);
for (int i = 0; i < 3; i++) { for (int i = 0; i < 3; i++) {
CloseableHttpResponse response = httpclient.execute(targetHost, httpget, localContext); CloseableHttpResponse response = httpclient.execute(target, httpget, localContext);
try { try {
HttpEntity entity = response.getEntity();
System.out.println("----------------------------------------"); System.out.println("----------------------------------------");
System.out.println(response.getStatusLine()); System.out.println(response.getStatusLine());
if (entity != null) { EntityUtils.consume(response.getEntity());
System.out.println("Response content length: " + entity.getContentLength());
}
EntityUtils.consume(entity);
} finally { } finally {
response.close(); response.close();
} }

View File

@ -26,7 +26,6 @@
*/ */
package org.apache.http.examples.client; package org.apache.http.examples.client;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHost; import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope; import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials; import org.apache.http.auth.UsernamePasswordCredentials;
@ -53,13 +52,14 @@ import org.apache.http.util.EntityUtils;
public class ClientPreemptiveDigestAuthentication { public class ClientPreemptiveDigestAuthentication {
public static void main(String[] args) throws Exception { public static void main(String[] args) throws Exception {
HttpHost targetHost = new HttpHost("localhost", 80, "http"); HttpHost target = new HttpHost("localhost", 80, "http");
CredentialsProvider credsProvider = new BasicCredentialsProvider(); CredentialsProvider credsProvider = new BasicCredentialsProvider();
credsProvider.setCredentials( credsProvider.setCredentials(
new AuthScope(targetHost.getHostName(), targetHost.getPort()), new AuthScope(target.getHostName(), target.getPort()),
new UsernamePasswordCredentials("username", "password")); new UsernamePasswordCredentials("username", "password"));
CloseableHttpClient httpclient = HttpClients.custom() CloseableHttpClient httpclient = HttpClients.custom()
.setDefaultCredentialsProvider(credsProvider).build(); .setDefaultCredentialsProvider(credsProvider)
.build();
try { try {
// Create AuthCache instance // Create AuthCache instance
@ -71,7 +71,7 @@ public class ClientPreemptiveDigestAuthentication {
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(target, digestAuth);
// Add AuthCache to the execution context // Add AuthCache to the execution context
HttpClientContext localContext = HttpClientContext.create(); HttpClientContext localContext = HttpClientContext.create();
@ -79,20 +79,13 @@ public class ClientPreemptiveDigestAuthentication {
HttpGet httpget = new HttpGet("/"); HttpGet httpget = new HttpGet("/");
System.out.println("executing request: " + httpget.getRequestLine()); System.out.println("Executing request " + httpget.getRequestLine() + " to target " + target);
System.out.println("to target: " + targetHost);
for (int i = 0; i < 3; i++) { for (int i = 0; i < 3; i++) {
CloseableHttpResponse response = httpclient.execute(targetHost, httpget, localContext); CloseableHttpResponse response = httpclient.execute(target, httpget, localContext);
try { try {
HttpEntity entity = response.getEntity();
System.out.println("----------------------------------------"); System.out.println("----------------------------------------");
System.out.println(response.getStatusLine()); System.out.println(response.getStatusLine());
if (entity != null) { EntityUtils.consume(response.getEntity());
System.out.println("Response content length: " + entity.getContentLength());
}
EntityUtils.consume(entity);
} finally { } finally {
response.close(); response.close();
} }

View File

@ -26,7 +26,6 @@
*/ */
package org.apache.http.examples.client; package org.apache.http.examples.client;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHost; import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope; import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials; import org.apache.http.auth.UsernamePasswordCredentials;
@ -53,7 +52,7 @@ public class ClientProxyAuthentication {
CloseableHttpClient httpclient = HttpClients.custom() CloseableHttpClient httpclient = HttpClients.custom()
.setDefaultCredentialsProvider(credsProvider).build(); .setDefaultCredentialsProvider(credsProvider).build();
try { try {
HttpHost targetHost = new HttpHost("www.verisign.com", 443, "https"); HttpHost target = new HttpHost("www.verisign.com", 443, "https");
HttpHost proxy = new HttpHost("localhost", 8080); HttpHost proxy = new HttpHost("localhost", 8080);
RequestConfig config = RequestConfig.custom() RequestConfig config = RequestConfig.custom()
@ -62,20 +61,13 @@ public class ClientProxyAuthentication {
HttpGet httpget = new HttpGet("/"); HttpGet httpget = new HttpGet("/");
httpget.setConfig(config); httpget.setConfig(config);
System.out.println("executing request: " + httpget.getRequestLine()); System.out.println("Executing request " + httpget.getRequestLine() + " to " + target + " via " + proxy);
System.out.println("via proxy: " + proxy);
System.out.println("to target: " + targetHost);
CloseableHttpResponse response = httpclient.execute(targetHost, httpget); CloseableHttpResponse response = httpclient.execute(target, httpget);
try { try {
HttpEntity entity = response.getEntity();
System.out.println("----------------------------------------"); System.out.println("----------------------------------------");
System.out.println(response.getStatusLine()); System.out.println(response.getStatusLine());
if (entity != null) { EntityUtils.consume(response.getEntity());
System.out.println("Response content length: " + entity.getContentLength());
}
EntityUtils.consume(entity);
} finally { } finally {
response.close(); response.close();
} }

View File

@ -47,9 +47,9 @@ public class ClientWithResponseHandler {
public final static void main(String[] args) throws Exception { public final static void main(String[] args) throws Exception {
CloseableHttpClient httpclient = HttpClients.createDefault(); CloseableHttpClient httpclient = HttpClients.createDefault();
try { try {
HttpGet httpget = new HttpGet("http://www.google.com/"); HttpGet httpget = new HttpGet("http://localhost/");
System.out.println("executing request " + httpget.getURI()); System.out.println("Executing request " + httpget.getRequestLine());
// Create a custom response handler // Create a custom response handler
ResponseHandler<String> responseHandler = new ResponseHandler<String>() { ResponseHandler<String> responseHandler = new ResponseHandler<String>() {
@ -69,8 +69,6 @@ public class ClientWithResponseHandler {
String responseBody = httpclient.execute(httpget, responseHandler); String responseBody = httpclient.execute(httpget, responseHandler);
System.out.println("----------------------------------------"); System.out.println("----------------------------------------");
System.out.println(responseBody); System.out.println(responseBody);
System.out.println("----------------------------------------");
} finally { } finally {
httpclient.close(); httpclient.close();
} }