Dedicated branch for testing maven-notice-plugin

git-svn-id: https://svn.apache.org/repos/asf/httpcomponents/httpclient/branches/notice-plugin-test@1026503 13f79535-47bb-0310-9956-ffa450edef68
This commit is contained in:
Oleg Kalnichevski 2010-10-22 21:47:45 +00:00
parent e4d6204517
commit c76574f947
37 changed files with 505 additions and 387 deletions

View File

@ -38,15 +38,7 @@
HttpComponents HttpClient - Benchmarks
</description>
<url>http://hc.apache.org/httpcomponents-client</url>
<packaging>jar</packaging>
<licenses>
<license>
<name>Apache License</name>
<url>../LICENSE.txt</url>
<distribution>repo</distribution>
</license>
</licenses>
<packaging>jar</packaging>
<dependencies>
<dependency>
@ -126,7 +118,7 @@
<goal>java</goal>
</goals>
<configuration>
<mainClass>org.apache.http.client.benchmark.Benchmark</mainClass>
<mainClass>org.apache.http.client.benchmark.Benchmark</mainClass>
</configuration>
</execution>
</executions>

View File

@ -40,13 +40,6 @@
<url>http://hc.apache.org/httpcomponents-client</url>
<packaging>jar</packaging>
<licenses>
<license>
<name>Apache License</name>
<url>../LICENSE.txt</url>
<distribution>repo</distribution>
</license>
</licenses>
<repositories>
<repository>
<id>spy</id>
@ -122,13 +115,6 @@
<build>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>false</filtering>
<includes>
<include>META-INF/*</include>
</includes>
</resource>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
@ -136,21 +122,6 @@
<include>**/*.properties</include>
</includes>
</resource>
<resource>
<directory>..</directory>
<targetPath>META-INF</targetPath>
<includes>
<include>LICENSE.txt</include>
</includes>
</resource>
<resource>
<directory>../src/main/resources</directory>
<targetPath>META-INF</targetPath>
<filtering>true</filtering>
<includes>
<include>NOTICE.txt</include>
</includes>
</resource>
</resources>
<plugins>
<plugin>

View File

@ -47,10 +47,25 @@ public class CacheConfig {
*/
public final static int DEFAULT_MAX_UPDATE_RETRIES = 1;
/** Default setting for heuristic caching
*/
public final static boolean DEFAULT_HEURISTIC_CACHING_ENABLED = false;
/** Default coefficient used to heuristically determine freshness lifetime from
* cache entry.
*/
public final static float DEFAULT_HEURISTIC_COEFFICIENT = 0.1f;
/** Default lifetime to be assumed when we cannot calculate freshness heuristically
*/
public final static long DEFAULT_HEURISTIC_LIFETIME = 0;
private int maxObjectSizeBytes = DEFAULT_MAX_OBJECT_SIZE_BYTES;
private int maxCacheEntries = DEFAULT_MAX_CACHE_ENTRIES;
private int maxUpdateRetries = DEFAULT_MAX_UPDATE_RETRIES;
private boolean heuristicCachingEnabled = false;
private float heuristicCoefficient = DEFAULT_HEURISTIC_COEFFICIENT;
private long heuristicDefaultLifetime = DEFAULT_HEURISTIC_LIFETIME;
private boolean isSharedCache = true;
/**
@ -118,4 +133,55 @@ public class CacheConfig {
public void setMaxUpdateRetries(int maxUpdateRetries){
this.maxUpdateRetries = maxUpdateRetries;
}
/**
* Returns if heuristic freshness caching is in enabled
* @return
*/
public boolean isHeuristicCachingEnabled() {
return heuristicCachingEnabled;
}
/**
* Set if heuristic freshness caching is enabled
* @param heursiticCachingEnabled
*/
public void setHeuristicCachingEnabled(boolean heuristicCachingEnabled) {
this.heuristicCachingEnabled = heuristicCachingEnabled;
}
/**
* Returns coefficient used in heuristic freshness caching
* @return
*/
public float getHeuristicCoefficient() {
return heuristicCoefficient;
}
/**
* Set coefficient to be used in heuristic freshness caching
* @param heuristicCoefficient
*/
public void setHeuristicCoefficient(float heuristicCoefficient) {
this.heuristicCoefficient = heuristicCoefficient;
}
/**
* Get the default lifetime to be used if heuristic freshness calculation is
* not possible
* @return
*/
public long getHeuristicDefaultLifetime() {
return heuristicDefaultLifetime;
}
/**
* Set default lifetime to be used if heuristic freshness calculation is not possible
* @param heuristicDefaultLifetime
*/
public void setHeuristicDefaultLifetime(long heuristicDefaultLifetime) {
this.heuristicDefaultLifetime = heuristicDefaultLifetime;
}
}

View File

@ -73,6 +73,39 @@ class CacheValidityPolicy {
return (getCurrentAgeSecs(entry, now) < getFreshnessLifetimeSecs(entry));
}
/**
* Decides if this response is fresh enough based Last-Modified and Date, if available.
* This entry is meant to be used when isResponseFresh returns false. The algorithm is as follows:
*
* if last-modified and date are defined, freshness lifetime is coefficient*(date-lastModified),
* else freshness lifetime is defaultLifetime
*
* @param entry
* @param now
* @param coefficient
* @param defaultLifetime
* @return
*/
public boolean isResponseHeuristicallyFresh(final HttpCacheEntry entry,
Date now, float coefficient, long defaultLifetime) {
return (getCurrentAgeSecs(entry, now) < getHeuristicFreshnessLifetimeSecs(entry, coefficient, defaultLifetime));
}
public long getHeuristicFreshnessLifetimeSecs(HttpCacheEntry entry,
float coefficient, long defaultLifetime) {
Date dateValue = getDateValue(entry);
Date lastModifiedValue = getLastModifiedValue(entry);
if (dateValue != null && lastModifiedValue != null) {
long diff = dateValue.getTime() - lastModifiedValue.getTime();
if (diff < 0)
return 0;
return (long)(coefficient * (diff / 1000));
}
return defaultLifetime;
}
public boolean isRevalidatable(final HttpCacheEntry entry) {
return entry.getFirstHeader(HeaderConstants.ETAG) != null
|| entry.getFirstHeader(HeaderConstants.LAST_MODIFIED) != null;
@ -98,6 +131,18 @@ class CacheValidityPolicy {
return null;
}
protected Date getLastModifiedValue(final HttpCacheEntry entry) {
Header dateHdr = entry.getFirstHeader(HeaderConstants.LAST_MODIFIED);
if (dateHdr == null)
return null;
try {
return DateUtils.parseDate(dateHdr.getValue());
} catch (DateParseException dpe) {
// ignore malformed date
}
return null;
}
protected long getContentLengthValue(final HttpCacheEntry entry) {
Header cl = entry.getFirstHeader(HTTP.CONTENT_LEN);
if (cl == null)

View File

@ -52,6 +52,9 @@ class CachedResponseSuitabilityChecker {
private final Log log = LogFactory.getLog(getClass());
private final boolean sharedCache;
private final boolean useHeuristicCaching;
private final float heuristicCoefficient;
private final long heuristicDefaultLifetime;
private final CacheValidityPolicy validityStrategy;
CachedResponseSuitabilityChecker(final CacheValidityPolicy validityStrategy,
@ -59,6 +62,9 @@ class CachedResponseSuitabilityChecker {
super();
this.validityStrategy = validityStrategy;
this.sharedCache = config.isSharedCache();
this.useHeuristicCaching = config.isHeuristicCachingEnabled();
this.heuristicCoefficient = config.getHeuristicCoefficient();
this.heuristicDefaultLifetime = config.getHeuristicDefaultLifetime();
}
CachedResponseSuitabilityChecker(CacheConfig config) {
@ -67,6 +73,9 @@ class CachedResponseSuitabilityChecker {
private boolean isFreshEnough(HttpCacheEntry entry, HttpRequest request, Date now) {
if (validityStrategy.isResponseFresh(entry, now)) return true;
if (useHeuristicCaching &&
validityStrategy.isResponseHeuristicallyFresh(entry, now, heuristicCoefficient, heuristicDefaultLifetime))
return true;
if (originInsistsOnFreshness(entry)) return false;
long maxstale = getMaxStale(request);
if (maxstale == -1) return false;

View File

@ -407,6 +407,11 @@ public class CachingHttpClient implements HttpClient {
log.debug("Cache miss [host: " + target + "; uri: " + rl.getUri() + "]");
}
if (!mayCallBackend(request)) {
return new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_GATEWAY_TIMEOUT,
"Gateway Timeout");
}
Set<HttpCacheEntry> variantEntries = null;
try {
responseCache.getVariantCacheEntries(target, request);
@ -447,6 +452,11 @@ public class CachingHttpClient implements HttpClient {
return cachedResponse;
}
if (!mayCallBackend(request)) {
return new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_GATEWAY_TIMEOUT,
"Gateway Timeout");
}
if (validityPolicy.isRevalidatable(entry)) {
log.debug("Revalidating the cache entry");
@ -472,6 +482,17 @@ public class CachingHttpClient implements HttpClient {
return callBackend(target, request, context);
}
private boolean mayCallBackend(HttpRequest request) {
for (Header h: request.getHeaders("Cache-Control")) {
for (HeaderElement elt : h.getElements()) {
if ("only-if-cached".equals(elt.getName())) {
return false;
}
}
}
return true;
}
private boolean explicitFreshnessRequest(HttpRequest request, HttpCacheEntry entry, Date now) {
for(Header h : request.getHeaders("Cache-Control")) {
for(HeaderElement elt : h.getElements()) {

View File

@ -250,6 +250,48 @@ public class TestCacheValidityPolicy {
Assert.assertEquals(4, impl.getFreshnessLifetimeSecs(entry));
}
@Test
public void testHeuristicFreshnessLifetime() {
Date now = new Date();
Date oneSecondAgo = new Date(now.getTime() - 1 * 1000L);
Date elevenSecondsAgo = new Date(now.getTime() - 11 * 1000L);
Header[] headers = new Header[] {
new BasicHeader("Date", DateUtils.formatDate(oneSecondAgo)),
new BasicHeader("Last-Modified", DateUtils.formatDate(elevenSecondsAgo))
};
HttpCacheEntry entry = HttpTestUtils.makeCacheEntry(headers);
CacheValidityPolicy impl = new CacheValidityPolicy();
Assert.assertEquals(1, impl.getHeuristicFreshnessLifetimeSecs(entry, 0.1f, 0));
}
@Test
public void testHeuristicFreshnessLifetimeDefaultsProperly() {
long defaultFreshness = 10;
HttpCacheEntry entry = HttpTestUtils.makeCacheEntry();
CacheValidityPolicy impl = new CacheValidityPolicy();
Assert.assertEquals(defaultFreshness, impl.getHeuristicFreshnessLifetimeSecs(entry, 0.1f, defaultFreshness));
}
@Test
public void testHeuristicFreshnessLifetimeIsNonNegative() {
Date now = new Date();
Date oneSecondAgo = new Date(now.getTime() - 1 * 1000L);
Date elevenSecondsAgo = new Date(now.getTime() - 1 * 1000L);
Header[] headers = new Header[] {
new BasicHeader("Date", DateUtils.formatDate(elevenSecondsAgo)),
new BasicHeader("Last-Modified", DateUtils.formatDate(oneSecondAgo))
};
HttpCacheEntry entry = HttpTestUtils.makeCacheEntry(headers);
CacheValidityPolicy impl = new CacheValidityPolicy();
Assert.assertTrue(impl.getHeuristicFreshnessLifetimeSecs(entry, 0.1f, 10) >= 0);
}
@Test
public void testResponseIsFreshIfFreshnessLifetimeExceedsCurrentAge() {
final HttpCacheEntry entry = HttpTestUtils.makeCacheEntry();

View File

@ -223,4 +223,41 @@ public class TestCachedResponseSuitabilityChecker {
Assert.assertFalse(impl.canCachedResponseBeUsed(host, request, entry, now));
}
@Test
public void testSuitableIfCacheEntryIsHeuristicallyFreshEnough() {
Date oneSecondAgo = new Date(now.getTime() - 1 * 1000L);
Date twentyOneSecondsAgo = new Date(now.getTime() - 21 * 1000L);
Header[] headers = {
new BasicHeader("Date", DateUtils.formatDate(oneSecondAgo)),
new BasicHeader("Last-Modified", DateUtils.formatDate(twentyOneSecondsAgo)),
new BasicHeader("Content-Length", "128")
};
entry = HttpTestUtils.makeCacheEntry(oneSecondAgo, oneSecondAgo, headers);
CacheConfig config = new CacheConfig();
config.setHeuristicCachingEnabled(true);
config.setHeuristicCoefficient(0.1f);
impl = new CachedResponseSuitabilityChecker(config);
Assert.assertTrue(impl.canCachedResponseBeUsed(host, request, entry, now));
}
@Test
public void testSuitableIfCacheEntryIsHeuristicallyFreshEnoughByDefault() {
Header[] headers = {
new BasicHeader("Date", DateUtils.formatDate(tenSecondsAgo)),
new BasicHeader("Content-Length", "128")
};
entry = getEntry(headers);
CacheConfig config = new CacheConfig();
config.setHeuristicCachingEnabled(true);
config.setHeuristicDefaultLifetime(20);
impl = new CachedResponseSuitabilityChecker(config);
Assert.assertTrue(impl.canCachedResponseBeUsed(host, request, entry, now));
}
}

View File

@ -1931,6 +1931,59 @@ public class TestCachingHttpClient {
Assert.assertSame(resp, result);
}
@Test
public void testIfOnlyIfCachedAndNoCacheEntryBackendNotCalled() throws IOException {
impl = new CachingHttpClient(mockBackend);
request.addHeader("Cache-Control", "only-if-cached");
HttpResponse resp = impl.execute(host, request);
Assert.assertEquals(HttpStatus.SC_GATEWAY_TIMEOUT, resp.getStatusLine().getStatusCode());
}
@Test
public void testIfOnlyIfCachedAndEntryNotSuitableBackendNotCalled() throws Exception {
request.setHeader("Cache-Control", "only-if-cached");
entry = HttpTestUtils.makeCacheEntry(new Header[]{new BasicHeader("Cache-Control", "must-revalidate")});
requestIsFatallyNonCompliant(null);
requestProtocolValidationIsCalled();
cacheInvalidatorWasCalled();
requestPolicyAllowsCaching(true);
getCacheEntryReturns(entry);
cacheEntrySuitable(false);
replayMocks();
HttpResponse resp = impl.execute(host, request);
verifyMocks();
Assert.assertEquals(HttpStatus.SC_GATEWAY_TIMEOUT, resp.getStatusLine().getStatusCode());
}
@Test
public void testIfOnlyIfCachedAndEntryExistsAndIsSuitableReturnsEntry() throws Exception {
request.setHeader("Cache-Control", "only-if-cached");
requestIsFatallyNonCompliant(null);
requestProtocolValidationIsCalled();
cacheInvalidatorWasCalled();
requestPolicyAllowsCaching(true);
getCacheEntryReturns(entry);
cacheEntrySuitable(true);
responseIsGeneratedFromCache();
entryHasStaleness(0);
replayMocks();
HttpResponse resp = impl.execute(host, request);
verifyMocks();
Assert.assertSame(mockCachedResponse, resp);
}
private void getCacheEntryReturns(HttpCacheEntry result) throws IOException {
EasyMock.expect(mockCache.getCacheEntry(host, request)).andReturn(result);
}

View File

@ -38,15 +38,7 @@
HttpComponents HttpClient - Contributed Components
</description>
<url>http://hc.apache.org/httpcomponents-client</url>
<packaging>jar</packaging>
<licenses>
<license>
<name>Apache License</name>
<url>../LICENSE.txt</url>
<distribution>repo</distribution>
</license>
</licenses>
<packaging>jar</packaging>
<dependencies>
<dependency>

View File

@ -1,5 +1,5 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
<!--
====================================================================
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
@ -39,7 +39,7 @@
HttpComponents Client (OSGi bundle)
</description>
<url>http://hc.apache.org/httpcomponents-client</url>
<packaging>bundle</packaging>
<packaging>bundle</packaging>
<licenses>
<license>
@ -79,13 +79,6 @@
<build>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>false</filtering>
<includes>
<include>META-INF/*</include>
</includes>
</resource>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
@ -93,21 +86,6 @@
<include>**/*.properties</include>
</includes>
</resource>
<resource>
<directory>..</directory>
<targetPath>META-INF</targetPath>
<includes>
<include>LICENSE.txt</include>
</includes>
</resource>
<resource>
<directory>../src/main/resources</directory>
<targetPath>META-INF</targetPath>
<filtering>true</filtering>
<includes>
<include>NOTICE.txt</include>
</includes>
</resource>
</resources>
<plugins>
<plugin>

View File

@ -38,15 +38,7 @@
HttpComponents Client (base module)
</description>
<url>http://hc.apache.org/httpcomponents-client</url>
<packaging>jar</packaging>
<licenses>
<license>
<name>Apache License</name>
<url>../LICENSE.txt</url>
<distribution>repo</distribution>
</license>
</licenses>
<packaging>jar</packaging>
<dependencies>
<dependency>
@ -98,13 +90,6 @@
<build>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>false</filtering>
<includes>
<include>META-INF/*</include>
</includes>
</resource>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
@ -112,46 +97,7 @@
<include>**/*.properties</include>
</includes>
</resource>
<resource>
<directory>..</directory>
<targetPath>META-INF</targetPath>
<includes>
<include>LICENSE.txt</include>
</includes>
</resource>
<resource>
<directory>../src/main/resources</directory>
<targetPath>META-INF</targetPath>
<filtering>true</filtering>
<includes>
<include>NOTICE.txt</include>
</includes>
</resource>
</resources>
<testResources>
<testResource>
<directory>src/test/resources</directory>
<filtering>false</filtering>
<includes>
<include>*</include>
</includes>
</testResource>
<testResource>
<directory>..</directory>
<targetPath>META-INF</targetPath>
<includes>
<include>LICENSE.txt</include>
</includes>
</testResource>
<testResource>
<directory>../src/main/resources</directory>
<targetPath>META-INF</targetPath>
<filtering>true</filtering>
<includes>
<include>NOTICE.txt</include>
</includes>
</testResource>
</testResources>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>

View File

@ -41,7 +41,7 @@ public class ClientAbortMethod {
public final static void main(String[] args) throws Exception {
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());
HttpResponse response = httpclient.execute(httpget);
@ -57,11 +57,11 @@ public class ClientAbortMethod {
// Do not feel like reading the response body
// Call abort on the request object
httpget.abort();
// When HttpClient instance is no longer needed,
// When HttpClient instance is no longer needed,
// shut down the connection manager to ensure
// immediate deallocation of all system resources
httpclient.getConnectionManager().shutdown();
httpclient.getConnectionManager().shutdown();
}
}

View File

@ -31,10 +31,11 @@ import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
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.
* a target site that requires user authentication.
*/
public class ClientAuthentication {
@ -42,11 +43,11 @@ public class ClientAuthentication {
DefaultHttpClient httpclient = new DefaultHttpClient();
httpclient.getCredentialsProvider().setCredentials(
new AuthScope("localhost", 443),
new AuthScope("localhost", 443),
new UsernamePasswordCredentials("username", "password"));
HttpGet httpget = new HttpGet("https://localhost/protected");
System.out.println("executing request" + httpget.getRequestLine());
HttpResponse response = httpclient.execute(httpget);
HttpEntity entity = response.getEntity();
@ -56,13 +57,11 @@ public class ClientAuthentication {
if (entity != null) {
System.out.println("Response content length: " + entity.getContentLength());
}
if (entity != null) {
entity.consumeContent();
}
EntityUtils.consume(entity);
// When HttpClient instance is no longer needed,
// When HttpClient instance is no longer needed,
// shut down the connection manager to ensure
// immediate deallocation of all system resources
httpclient.getConnectionManager().shutdown();
httpclient.getConnectionManager().shutdown();
}
}

View File

@ -21,7 +21,7 @@
* 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;
@ -35,6 +35,7 @@ import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.InputStreamEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
/**
* Example how to use unbuffered chunk-encoded POST request.
@ -57,14 +58,14 @@ public class ClientChunkEncodedPost {
new FileInputStream(file), -1);
reqEntity.setContentType("binary/octet-stream");
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
// 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);
System.out.println("executing request " + httppost.getRequestLine());
HttpResponse response = httpclient.execute(httppost);
HttpEntity resEntity = response.getEntity();
@ -75,14 +76,12 @@ public class ClientChunkEncodedPost {
System.out.println("Response content length: " + resEntity.getContentLength());
System.out.println("Chunked?: " + resEntity.isChunked());
}
if (resEntity != null) {
resEntity.consumeContent();
}
EntityUtils.consume(resEntity);
// When HttpClient instance is no longer needed,
// When HttpClient instance is no longer needed,
// shut down the connection manager to ensure
// immediate deallocation of all system resources
httpclient.getConnectionManager().shutdown();
httpclient.getConnectionManager().shutdown();
}
}

View File

@ -40,27 +40,28 @@ import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.HttpContext;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.util.EntityUtils;
/**
* This example demonstrates the use of a local HTTP context populated with
* This example demonstrates the use of a local HTTP context populated with
* custom attributes.
*/
public class ClientCustomContext {
public final static void main(String[] args) throws Exception {
HttpClient httpclient = new DefaultHttpClient();
// Create a local instance of cookie store
CookieStore cookieStore = new BasicCookieStore();
// Create local HTTP context
HttpContext localContext = new BasicHttpContext();
// Bind custom cookie store to the local context
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());
@ -77,19 +78,17 @@ public class ClientCustomContext {
for (int i = 0; i < cookies.size(); i++) {
System.out.println("Local cookie: " + cookies.get(i));
}
// Consume response content
if (entity != null) {
entity.consumeContent();
}
EntityUtils.consume(entity);
System.out.println("----------------------------------------");
// When HttpClient instance is no longer needed,
// When HttpClient instance is no longer needed,
// shut down the connection manager to ensure
// immediate deallocation of all system resources
httpclient.getConnectionManager().shutdown();
httpclient.getConnectionManager().shutdown();
}
}

View File

@ -36,6 +36,7 @@ import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
/**
* This example demonstrates how to create secure connections with a custom SSL
@ -46,14 +47,14 @@ public class ClientCustomSSL {
public final static void main(String[] args) throws Exception {
DefaultHttpClient httpclient = new DefaultHttpClient();
KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
FileInputStream instream = new FileInputStream(new File("my.keystore"));
KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
FileInputStream instream = new FileInputStream(new File("my.keystore"));
try {
trustStore.load(instream, "nopassword".toCharArray());
} finally {
instream.close();
}
SSLSocketFactory socketFactory = new SSLSocketFactory(trustStore);
Scheme sch = new Scheme("https", 443, socketFactory);
httpclient.getConnectionManager().getSchemeRegistry().register(sch);
@ -61,7 +62,7 @@ public class ClientCustomSSL {
HttpGet httpget = new HttpGet("https://localhost/");
System.out.println("executing request" + httpget.getRequestLine());
HttpResponse response = httpclient.execute(httpget);
HttpEntity entity = response.getEntity();
@ -70,14 +71,12 @@ public class ClientCustomSSL {
if (entity != null) {
System.out.println("Response content length: " + entity.getContentLength());
}
if (entity != null) {
entity.consumeContent();
}
EntityUtils.consume(entity);
// When HttpClient instance is no longer needed,
// When HttpClient instance is no longer needed,
// shut down the connection manager to ensure
// immediate deallocation of all system resources
httpclient.getConnectionManager().shutdown();
httpclient.getConnectionManager().shutdown();
}
}

View File

@ -23,7 +23,7 @@
* <http://www.apache.org/>.
*
*/
package org.apache.http.examples.client;
import java.util.concurrent.TimeUnit;
@ -38,6 +38,7 @@ import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.util.EntityUtils;
/**
* Example demonstrating how to evict expired and idle connections
@ -46,16 +47,16 @@ import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
public class ClientEvictExpiredConnections {
public static void main(String[] args) throws Exception {
// Create and initialize scheme registry
// Create and initialize scheme registry
SchemeRegistry schemeRegistry = new SchemeRegistry();
schemeRegistry.register(
new Scheme("http", 80, PlainSocketFactory.getSocketFactory()));
ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager(schemeRegistry);
cm.setMaxTotalConnections(100);
cm.setMaxTotal(100);
HttpClient httpclient = new DefaultHttpClient(cm);
// create an array of URIs to perform GETs on
String[] urisToGet = {
"http://jakarta.apache.org/",
@ -63,10 +64,10 @@ public class ClientEvictExpiredConnections {
"http://jakarta.apache.org/commons/httpclient/",
"http://svn.apache.org/viewvc/jakarta/httpcomponents/"
};
IdleConnectionEvictor connEvictor = new IdleConnectionEvictor(cm);
connEvictor.start();
for (int i = 0; i < urisToGet.length; i++) {
String requestURI = urisToGet[i];
HttpGet req = new HttpGet(requestURI);
@ -83,30 +84,28 @@ public class ClientEvictExpiredConnections {
}
System.out.println("----------------------------------------");
if (entity != null) {
entity.consumeContent();
}
EntityUtils.consume(entity);
}
// Sleep 10 sec and let the connection evictor do its job
Thread.sleep(20000);
// Shut down the evictor thread
connEvictor.shutdown();
connEvictor.join();
// When HttpClient instance is no longer needed,
// When HttpClient instance is no longer needed,
// shut down the connection manager to ensure
// immediate deallocation of all system resources
httpclient.getConnectionManager().shutdown();
httpclient.getConnectionManager().shutdown();
}
public static class IdleConnectionEvictor extends Thread {
private final ClientConnectionManager connMgr;
private volatile boolean shutdown;
public IdleConnectionEvictor(ClientConnectionManager connMgr) {
super();
this.connMgr = connMgr;
@ -129,14 +128,14 @@ public class ClientEvictExpiredConnections {
// terminate
}
}
public void shutdown() {
shutdown = true;
synchronized (this) {
notifyAll();
}
}
}
}

View File

@ -38,7 +38,7 @@ import org.apache.http.util.EntityUtils;
/**
* How to send a request directly using {@link HttpClient}.
*
*
* @since 4.0
*/
public class ClientExecuteDirect {
@ -66,10 +66,10 @@ public class ClientExecuteDirect {
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
// immediate deallocation of all system resources
httpclient.getConnectionManager().shutdown();
httpclient.getConnectionManager().shutdown();
}
}

View File

@ -69,10 +69,10 @@ public class ClientExecuteProxy {
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
// immediate deallocation of all system resources
httpclient.getConnectionManager().shutdown();
httpclient.getConnectionManager().shutdown();
}
}

View File

@ -81,12 +81,12 @@ public class ClientExecuteSOCKS {
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
// immediate deallocation of all system resources
httpclient.getConnectionManager().shutdown();
httpclient.getConnectionManager().shutdown();
}
static class MySchemeSocketFactory implements SchemeSocketFactory {
public Socket createSocket(final HttpParams params) throws IOException {
@ -96,16 +96,16 @@ public class ClientExecuteSOCKS {
String proxyHost = (String) params.getParameter("socks.host");
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);
return new Socket(proxy);
}
public Socket connectSocket(
final Socket socket,
final Socket socket,
final InetSocketAddress remoteAddress,
final InetSocketAddress localAddress,
final HttpParams params)
final InetSocketAddress localAddress,
final HttpParams params)
throws IOException, UnknownHostException, ConnectTimeoutException {
if (remoteAddress == null) {
throw new IllegalArgumentException("Remote address may not be null");
@ -127,7 +127,7 @@ public class ClientExecuteSOCKS {
try {
sock.connect(remoteAddress, timeout);
} catch (SocketTimeoutException ex) {
throw new ConnectTimeoutException("Connect to " + remoteAddress.getHostName() + "/"
throw new ConnectTimeoutException("Connect to " + remoteAddress.getHostName() + "/"
+ remoteAddress.getAddress() + " timed out");
}
return sock;
@ -136,7 +136,7 @@ public class ClientExecuteSOCKS {
public boolean isSecure(final Socket sock) throws IllegalArgumentException {
return false;
}
}
}

View File

@ -38,6 +38,7 @@ import org.apache.http.cookie.Cookie;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
/**
* A example that demonstrates how HttpClient APIs can be used to perform
@ -55,9 +56,8 @@ public class ClientFormLogin {
HttpEntity entity = response.getEntity();
System.out.println("Login form get: " + response.getStatusLine());
if (entity != null) {
entity.consumeContent();
}
EntityUtils.consume(entity);
System.out.println("Initial set of cookies:");
List<Cookie> cookies = httpclient.getCookieStore().getCookies();
if (cookies.isEmpty()) {
@ -83,9 +83,7 @@ public class ClientFormLogin {
entity = response.getEntity();
System.out.println("Login form get: " + response.getStatusLine());
if (entity != null) {
entity.consumeContent();
}
EntityUtils.consume(entity);
System.out.println("Post logon cookies:");
cookies = httpclient.getCookieStore().getCookies();
@ -97,9 +95,9 @@ public class ClientFormLogin {
}
}
// When HttpClient instance is no longer needed,
// When HttpClient instance is no longer needed,
// shut down the connection manager to ensure
// immediate deallocation of all system resources
httpclient.getConnectionManager().shutdown();
httpclient.getConnectionManager().shutdown();
}
}

View File

@ -46,15 +46,15 @@ import org.apache.http.protocol.HttpContext;
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.
* <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
* 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
* protocol interceptors makes content compression completely transparent to
* the consumer of the {@link org.apache.http.client.HttpClient HttpClient}
* interface.
*/
@ -64,9 +64,9 @@ public class ClientGZipContentCompression {
DefaultHttpClient httpclient = new DefaultHttpClient();
httpclient.addRequestInterceptor(new HttpRequestInterceptor() {
public void process(
final HttpRequest request,
final HttpRequest request,
final HttpContext context) throws HttpException, IOException {
if (!request.containsHeader("Accept-Encoding")) {
request.addHeader("Accept-Encoding", "gzip");
@ -74,11 +74,11 @@ public class ClientGZipContentCompression {
}
});
httpclient.addResponseInterceptor(new HttpResponseInterceptor() {
public void process(
final HttpResponse response,
final HttpResponse response,
final HttpContext context) throws HttpException, IOException {
HttpEntity entity = response.getEntity();
Header ceheader = entity.getContentEncoding();
@ -87,17 +87,17 @@ public class ClientGZipContentCompression {
for (int i = 0; i < codecs.length; i++) {
if (codecs[i].getName().equalsIgnoreCase("gzip")) {
response.setEntity(
new GzipDecompressingEntity(response.getEntity()));
new GzipDecompressingEntity(response.getEntity()));
return;
}
}
}
}
});
HttpGet httpget = new HttpGet("http://www.apache.org/");
HttpGet httpget = new HttpGet("http://www.apache.org/");
// Execute HTTP request
System.out.println("executing request " + httpget.getURI());
HttpResponse response = httpclient.execute(httpget);
@ -109,7 +109,7 @@ public class ClientGZipContentCompression {
System.out.println("----------------------------------------");
HttpEntity entity = response.getEntity();
if (entity != null) {
String content = EntityUtils.toString(entity);
System.out.println(content);
@ -117,10 +117,10 @@ public class ClientGZipContentCompression {
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
// immediate deallocation of all system resources
httpclient.getConnectionManager().shutdown();
httpclient.getConnectionManager().shutdown();
}
static class GzipDecompressingEntity extends HttpEntityWrapper {
@ -128,7 +128,7 @@ public class ClientGZipContentCompression {
public GzipDecompressingEntity(final HttpEntity entity) {
super(entity);
}
@Override
public InputStream getContent()
throws IOException, IllegalStateException {
@ -145,7 +145,7 @@ public class ClientGZipContentCompression {
return -1;
}
}
}
}

View File

@ -40,10 +40,11 @@ import org.apache.http.client.protocol.ClientContext;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;
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.
* a target site that requires user authentication.
*/
public class ClientInteractiveAuthentication {
@ -54,7 +55,7 @@ public class ClientInteractiveAuthentication {
HttpContext localContext = new BasicHttpContext();
HttpGet httpget = new HttpGet("http://localhost/test");
boolean trying = true;
while (trying) {
System.out.println("executing request " + httpget.getRequestLine());
@ -65,37 +66,35 @@ public class ClientInteractiveAuthentication {
// Consume response content
HttpEntity entity = response.getEntity();
if (entity != null) {
entity.consumeContent();
}
EntityUtils.consume(entity);
int sc = response.getStatusLine().getStatusCode();
AuthState authState = null;
if (sc == HttpStatus.SC_UNAUTHORIZED) {
// Target host authentication required
authState = (AuthState) localContext.getAttribute(ClientContext.TARGET_AUTH_STATE);
}
}
if (sc == HttpStatus.SC_PROXY_AUTHENTICATION_REQUIRED) {
// Proxy authentication required
authState = (AuthState) localContext.getAttribute(ClientContext.PROXY_AUTH_STATE);
}
if (authState != null) {
System.out.println("----------------------------------------");
AuthScope authScope = authState.getAuthScope();
System.out.println("Please provide credentials");
System.out.println(" Host: " + authScope.getHost() + ":" + authScope.getPort());
System.out.println(" Realm: " + authScope.getRealm());
BufferedReader console = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter username: ");
String user = console.readLine();
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);
httpclient.getCredentialsProvider().setCredentials(authScope, creds);
@ -108,9 +107,9 @@ public class ClientInteractiveAuthentication {
}
}
// When HttpClient instance is no longer needed,
// When HttpClient instance is no longer needed,
// shut down the connection manager to ensure
// immediate deallocation of all system resources
httpclient.getConnectionManager().shutdown();
httpclient.getConnectionManager().shutdown();
}
}

View File

@ -40,9 +40,9 @@ import org.apache.http.util.EntityUtils;
/**
* Kerberos auth example.
*
*
* <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>
* <p><em>NegotiateSchemeFactory</em> kas two custom methods</p>
* <p><em>#setStripPort(boolean)</em> - default is false, with strip the port off the Kerberos
@ -92,7 +92,7 @@ import org.apache.http.util.EntityUtils;
* </pre>
* <p><b>Windows specific configuration</b></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.
* </p>
* <p>
@ -102,7 +102,7 @@ import org.apache.http.util.EntityUtils;
* HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\Lsa\Kerberos\Parameters
* Value Name: allowtgtsessionkey
* Value Type: REG_DWORD
* Value: 0x01
* Value: 0x01
* </pre>
* <p>
* Here is the location of the registry setting on Windows XP SP2:
@ -113,7 +113,7 @@ import org.apache.http.util.EntityUtils;
* Value Type: REG_DWORD
* Value: 0x01
* </pre>
*
*
* @since 4.1
*/
public class ClientKerberosAuthentication {
@ -124,13 +124,13 @@ public class ClientKerberosAuthentication {
System.setProperty("java.security.krb5.conf", "krb5.conf");
System.setProperty("sun.security.krb5.debug", "true");
System.setProperty("javax.security.auth.useSubjectCredsOnly","false");
DefaultHttpClient httpclient = new DefaultHttpClient();
NegotiateSchemeFactory nsf = new NegotiateSchemeFactory();
// nsf.setStripPort(false);
// nsf.setSpengoGenerator(new BouncySpnegoTokenGenerator());
httpclient.getAuthSchemes().register(AuthPolicy.SPNEGO, nsf);
Credentials use_jaas_creds = new Credentials() {
@ -142,7 +142,7 @@ public class ClientKerberosAuthentication {
public Principal getUserPrincipal() {
return null;
}
};
httpclient.getCredentialsProvider().setCredentials(
@ -160,16 +160,14 @@ public class ClientKerberosAuthentication {
System.out.println(EntityUtils.toString(entity));
}
System.out.println("----------------------------------------");
// This ensures the connection gets released back to the manager
if (entity != null) {
entity.consumeContent();
}
// When HttpClient instance is no longer needed,
// This ensures the connection gets released back to the manager
EntityUtils.consume(entity);
// When HttpClient instance is no longer needed,
// shut down the connection manager to ensure
// immediate deallocation of all system resources
httpclient.getConnectionManager().shutdown();
httpclient.getConnectionManager().shutdown();
}
}

View File

@ -23,7 +23,7 @@
* <http://www.apache.org/>.
*
*/
package org.apache.http.examples.client;
import org.apache.http.HttpEntity;
@ -41,24 +41,24 @@ import org.apache.http.util.EntityUtils;
/**
* An example that performs GETs from multiple threads.
*
*
*/
public class ClientMultiThreadedExecution {
public static void main(String[] args) throws Exception {
// Create and initialize scheme registry
// Create and initialize scheme registry
SchemeRegistry schemeRegistry = new SchemeRegistry();
schemeRegistry.register(
new Scheme("http", 80, PlainSocketFactory.getSocketFactory()));
// Create an HttpClient with the ThreadSafeClientConnManager.
// This connection manager must be used if more than one thread will
// be using the HttpClient.
ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager(schemeRegistry);
cm.setMaxTotalConnections(100);
cm.setMaxTotal(100);
HttpClient httpClient = new DefaultHttpClient(cm);
// create an array of URIs to perform GETs on
String[] urisToGet = {
"http://hc.apache.org/",
@ -66,60 +66,60 @@ public class ClientMultiThreadedExecution {
"http://hc.apache.org/httpcomponents-client/",
"http://svn.apache.org/viewvc/httpcomponents/"
};
// create a thread for each URI
GetThread[] threads = new GetThread[urisToGet.length];
for (int i = 0; i < threads.length; i++) {
HttpGet httpget = new HttpGet(urisToGet[i]);
threads[i] = new GetThread(httpClient, httpget, i + 1);
}
// start the threads
for (int j = 0; j < threads.length; j++) {
threads[j].start();
}
// join the threads
for (int j = 0; j < threads.length; j++) {
threads[j].join();
}
// When HttpClient instance is no longer needed,
// When HttpClient instance is no longer needed,
// shut down the connection manager to ensure
// immediate deallocation of all system resources
httpClient.getConnectionManager().shutdown();
httpClient.getConnectionManager().shutdown();
}
/**
* A thread that performs a GET.
*/
static class GetThread extends Thread {
private final HttpClient httpClient;
private final HttpContext context;
private final HttpGet httpget;
private final int id;
public GetThread(HttpClient httpClient, HttpGet httpget, int id) {
this.httpClient = httpClient;
this.context = new BasicHttpContext();
this.httpget = httpget;
this.id = id;
}
/**
* Executes the GetMethod and prints some status information.
*/
@Override
public void run() {
System.out.println(id + " - about to get something from " + httpget.getURI());
try {
// execute the method
HttpResponse response = httpClient.execute(httpget, context);
System.out.println(id + " - get executed");
// get the response body as an array of bytes
HttpEntity entity = response.getEntity();
@ -127,13 +127,13 @@ public class ClientMultiThreadedExecution {
byte[] bytes = EntityUtils.toByteArray(entity);
System.out.println(id + " - " + bytes.length + " bytes read");
}
} catch (Exception e) {
httpget.abort();
System.out.println(id + " - error: " + e);
}
}
}
}

View File

@ -37,9 +37,10 @@ import org.apache.http.impl.auth.BasicScheme;
import org.apache.http.impl.client.BasicAuthCache;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.BasicHttpContext;
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.
* <b/>
* Generally, preemptive authentication can be considered less
@ -50,30 +51,30 @@ public class ClientPreemptiveBasicAuthentication {
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();
httpclient.getCredentialsProvider().setCredentials(
new AuthScope(targetHost.getHostName(), targetHost.getPort()),
new AuthScope(targetHost.getHostName(), targetHost.getPort()),
new UsernamePasswordCredentials("username", "password"));
// Create AuthCache instance
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
BasicScheme basicAuth = new BasicScheme();
authCache.put(targetHost, basicAuth);
// Add AuthCache to the execution context
BasicHttpContext localcontext = new BasicHttpContext();
localcontext.setAttribute(ClientContext.AUTH_CACHE, authCache);
localcontext.setAttribute(ClientContext.AUTH_CACHE, authCache);
HttpGet httpget = new HttpGet("/");
System.out.println("executing request: " + httpget.getRequestLine());
System.out.println("to target: " + targetHost);
for (int i = 0; i < 3; i++) {
HttpResponse response = httpclient.execute(targetHost, httpget, localcontext);
HttpEntity entity = response.getEntity();
@ -82,14 +83,14 @@ public class ClientPreemptiveBasicAuthentication {
System.out.println(response.getStatusLine());
if (entity != null) {
System.out.println("Response content length: " + entity.getContentLength());
entity.consumeContent();
}
EntityUtils.consume(entity);
}
// When HttpClient instance is no longer needed,
// When HttpClient instance is no longer needed,
// shut down the connection manager to ensure
// immediate deallocation of all system resources
httpclient.getConnectionManager().shutdown();
httpclient.getConnectionManager().shutdown();
}
}

View File

@ -37,9 +37,10 @@ import org.apache.http.impl.auth.DigestScheme;
import org.apache.http.impl.client.BasicAuthCache;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.BasicHttpContext;
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.
* <b/>
* Generally, preemptive authentication can be considered less
@ -50,34 +51,34 @@ public class ClientPreemptiveDigestAuthentication {
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();
httpclient.getCredentialsProvider().setCredentials(
new AuthScope(targetHost.getHostName(), targetHost.getPort()),
new AuthScope(targetHost.getHostName(), targetHost.getPort()),
new UsernamePasswordCredentials("username", "password"));
// Create AuthCache instance
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
DigestScheme digestAuth = new DigestScheme();
// Suppose we already know the realm name
digestAuth.overrideParamter("realm", "some realm");
// Suppose we already know the expected nonce value
digestAuth.overrideParamter("nonce", "whatever");
digestAuth.overrideParamter("realm", "some realm");
// Suppose we already know the expected nonce value
digestAuth.overrideParamter("nonce", "whatever");
authCache.put(targetHost, digestAuth);
// Add AuthCache to the execution context
BasicHttpContext localcontext = new BasicHttpContext();
localcontext.setAttribute(ClientContext.AUTH_CACHE, authCache);
localcontext.setAttribute(ClientContext.AUTH_CACHE, authCache);
HttpGet httpget = new HttpGet("/");
System.out.println("executing request: " + httpget.getRequestLine());
System.out.println("to target: " + targetHost);
for (int i = 0; i < 3; i++) {
HttpResponse response = httpclient.execute(targetHost, httpget, localcontext);
HttpEntity entity = response.getEntity();
@ -86,14 +87,14 @@ public class ClientPreemptiveDigestAuthentication {
System.out.println(response.getStatusLine());
if (entity != null) {
System.out.println("Response content length: " + entity.getContentLength());
entity.consumeContent();
}
EntityUtils.consume(entity);
}
// When HttpClient instance is no longer needed,
// When HttpClient instance is no longer needed,
// shut down the connection manager to ensure
// immediate deallocation of all system resources
httpclient.getConnectionManager().shutdown();
httpclient.getConnectionManager().shutdown();
}
}

View File

@ -33,32 +33,33 @@ import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.params.ConnRoutePNames;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
/**
* A simple example that uses HttpClient to execute an HTTP request
* over a secure connection tunneled through an authenticating proxy.
* A simple example that uses HttpClient to execute an HTTP request
* over a secure connection tunneled through an authenticating proxy.
*/
public class ClientProxyAuthentication {
public static void main(String[] args) throws Exception {
DefaultHttpClient httpclient = new DefaultHttpClient();
httpclient.getCredentialsProvider().setCredentials(
new AuthScope("localhost", 8080),
new AuthScope("localhost", 8080),
new UsernamePasswordCredentials("username", "password"));
HttpHost targetHost = new HttpHost("www.verisign.com", 443, "https");
HttpHost proxy = new HttpHost("localhost", 8080);
HttpHost targetHost = new HttpHost("www.verisign.com", 443, "https");
HttpHost proxy = new HttpHost("localhost", 8080);
httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
HttpGet httpget = new HttpGet("/");
System.out.println("executing request: " + httpget.getRequestLine());
System.out.println("via proxy: " + proxy);
System.out.println("to target: " + targetHost);
HttpResponse response = httpclient.execute(targetHost, httpget);
HttpEntity entity = response.getEntity();
@ -67,13 +68,11 @@ public class ClientProxyAuthentication {
if (entity != null) {
System.out.println("Response content length: " + entity.getContentLength());
}
if (entity != null) {
entity.consumeContent();
}
// When HttpClient instance is no longer needed,
EntityUtils.consume(entity);
// When HttpClient instance is no longer needed,
// shut down the connection manager to ensure
// immediate deallocation of all system resources
httpclient.getConnectionManager().shutdown();
httpclient.getConnectionManager().shutdown();
}
}

View File

@ -34,16 +34,16 @@ import org.apache.http.impl.client.BasicResponseHandler;
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.
*/
public class ClientWithResponseHandler {
public final static void main(String[] args) throws Exception {
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());
@ -54,11 +54,11 @@ public class ClientWithResponseHandler {
System.out.println(responseBody);
System.out.println("----------------------------------------");
// When HttpClient instance is no longer needed,
// When HttpClient instance is no longer needed,
// shut down the connection manager to ensure
// immediate deallocation of all system resources
httpclient.getConnectionManager().shutdown();
httpclient.getConnectionManager().shutdown();
}
}

View File

@ -85,7 +85,7 @@ public class ManagerConnectDirect {
HttpRequest req = new BasicHttpRequest("OPTIONS", "*", HttpVersion.HTTP_1_1);
req.addHeader("Host", target.getHostName());
HttpContext ctx = new BasicHttpContext();
System.out.println("preparing route to " + target);

View File

@ -105,7 +105,7 @@ public class ManagerConnectProxy {
String authority = target.getHostName() + ":" + target.getPort();
HttpRequest connect = new BasicHttpRequest("CONNECT", authority, HttpVersion.HTTP_1_1);
connect.addHeader("Host", authority);
System.out.println("opening tunnel to " + target);
conn.sendRequestHeader(connect);
// there is no request entity

View File

@ -77,7 +77,7 @@ public class OperatorConnectDirect {
HttpRequest req = new BasicHttpRequest("OPTIONS", "*", HttpVersion.HTTP_1_1);
req.addHeader("Host", target.getHostName());
HttpContext ctx = new BasicHttpContext();
OperatedClientConnection conn = scop.createConnection();

View File

@ -67,9 +67,9 @@ public class OperatorConnectProxy {
// Register the "http" and "https" protocol schemes, they are
// required by the default operator to look up socket factories.
SchemeRegistry supportedSchemes = new SchemeRegistry();
supportedSchemes.register(new Scheme("http",
supportedSchemes.register(new Scheme("http",
80, PlainSocketFactory.getSocketFactory()));
supportedSchemes.register(new Scheme("https",
supportedSchemes.register(new Scheme("https",
443, SSLSocketFactory.getSocketFactory()));
// Prepare parameters.
@ -86,7 +86,7 @@ public class OperatorConnectProxy {
// In a real application, request interceptors should be used
// to add the required headers.
req.addHeader("Host", target.getHostName());
HttpContext ctx = new BasicHttpContext();
OperatedClientConnection conn = scop.createConnection();
@ -97,7 +97,7 @@ public class OperatorConnectProxy {
// Creates a request to tunnel a connection.
// For details see RFC 2817, section 5.2
String authority = target.getHostName() + ":" + target.getPort();
HttpRequest connect = new BasicHttpRequest("CONNECT", authority,
HttpRequest connect = new BasicHttpRequest("CONNECT", authority,
HttpVersion.HTTP_1_1);
// In a real application, request interceptors should be used
// to add the required headers.

View File

@ -38,15 +38,7 @@
HttpComponents HttpClient - MIME coded entities
</description>
<url>http://hc.apache.org/httpcomponents-client</url>
<packaging>jar</packaging>
<licenses>
<license>
<name>Apache License</name>
<url>../LICENSE.txt</url>
<distribution>repo</distribution>
</license>
</licenses>
<packaging>jar</packaging>
<dependencies>
<dependency>
@ -80,13 +72,6 @@
<build>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>false</filtering>
<includes>
<include>META-INF/*</include>
</includes>
</resource>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
@ -94,21 +79,6 @@
<include>**/*.properties</include>
</includes>
</resource>
<resource>
<directory>..</directory>
<targetPath>META-INF</targetPath>
<includes>
<include>LICENSE.txt</include>
</includes>
</resource>
<resource>
<directory>../src/main/resources</directory>
<targetPath>META-INF</targetPath>
<filtering>true</filtering>
<includes>
<include>NOTICE.txt</include>
</includes>
</resource>
</resources>
<plugins>
<plugin>

13
pom.xml
View File

@ -86,6 +86,19 @@
<build>
<plugins>
<plugin>
<artifactId>maven-notice-plugin</artifactId>
<groupId>org.apache.httpcomponents</groupId>
<version>0.0.1-SNAPSHOT</version>
<executions>
<execution>
<id>attach-notice-license</id>
<goals>
<goal>generate</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<artifactId>maven-source-plugin</artifactId>
<executions>

View File

@ -1,8 +0,0 @@
Apache HttpComponents Client - ${project.name}
Copyright 1999-2010 The Apache Software Foundation
This product includes software developed by
The Apache Software Foundation (http://www.apache.org/).
This project contains annotations derived from JCIP-ANNOTATIONS
Copyright (c) 2005 Brian Goetz and Tim Peierls. See http://www.jcip.net