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:
parent
922d442ce9
commit
d6ffa5362c
|
@ -27,7 +27,6 @@
|
|||
|
||||
package org.apache.http.examples.client;
|
||||
|
||||
import org.apache.http.HttpEntity;
|
||||
import org.apache.http.client.methods.CloseableHttpResponse;
|
||||
import org.apache.http.client.methods.HttpGet;
|
||||
import org.apache.http.impl.client.CloseableHttpClient;
|
||||
|
@ -43,18 +42,11 @@ public class ClientAbortMethod {
|
|||
try {
|
||||
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);
|
||||
try {
|
||||
HttpEntity entity = response.getEntity();
|
||||
|
||||
System.out.println("----------------------------------------");
|
||||
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
|
||||
// Call abort on the request object
|
||||
httpget.abort();
|
||||
|
|
|
@ -26,7 +26,6 @@
|
|||
*/
|
||||
package org.apache.http.examples.client;
|
||||
|
||||
import org.apache.http.HttpEntity;
|
||||
import org.apache.http.auth.AuthScope;
|
||||
import org.apache.http.auth.UsernamePasswordCredentials;
|
||||
import org.apache.http.client.CredentialsProvider;
|
||||
|
@ -49,21 +48,17 @@ public class ClientAuthentication {
|
|||
new AuthScope("localhost", 443),
|
||||
new UsernamePasswordCredentials("username", "password"));
|
||||
CloseableHttpClient httpclient = HttpClients.custom()
|
||||
.setDefaultCredentialsProvider(credsProvider).build();
|
||||
.setDefaultCredentialsProvider(credsProvider)
|
||||
.build();
|
||||
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);
|
||||
try {
|
||||
HttpEntity entity = response.getEntity();
|
||||
|
||||
System.out.println("----------------------------------------");
|
||||
System.out.println(response.getStatusLine());
|
||||
if (entity != null) {
|
||||
System.out.println("Response content length: " + entity.getContentLength());
|
||||
}
|
||||
EntityUtils.consume(entity);
|
||||
EntityUtils.consume(response.getEntity());
|
||||
} finally {
|
||||
response.close();
|
||||
}
|
||||
|
|
|
@ -29,9 +29,9 @@ package org.apache.http.examples.client;
|
|||
import java.io.File;
|
||||
import java.io.FileInputStream;
|
||||
|
||||
import org.apache.http.HttpEntity;
|
||||
import org.apache.http.client.methods.CloseableHttpResponse;
|
||||
import org.apache.http.client.methods.HttpPost;
|
||||
import org.apache.http.entity.ContentType;
|
||||
import org.apache.http.entity.InputStreamEntity;
|
||||
import org.apache.http.impl.client.CloseableHttpClient;
|
||||
import org.apache.http.impl.client.HttpClients;
|
||||
|
@ -49,14 +49,12 @@ public class ClientChunkEncodedPost {
|
|||
}
|
||||
CloseableHttpClient httpclient = HttpClients.createDefault();
|
||||
try {
|
||||
HttpPost httppost = new HttpPost("http://localhost:8080" +
|
||||
"/servlets-examples/servlet/RequestInfoExample");
|
||||
HttpPost httppost = new HttpPost("http://localhost/");
|
||||
|
||||
File file = new File(args[0]);
|
||||
|
||||
InputStreamEntity reqEntity = new InputStreamEntity(
|
||||
new FileInputStream(file), -1);
|
||||
reqEntity.setContentType("binary/octet-stream");
|
||||
new FileInputStream(file), -1, ContentType.APPLICATION_OCTET_STREAM);
|
||||
reqEntity.setChunked(true);
|
||||
// It may be more appropriate to use FileEntity class in this particular
|
||||
// instance but we are using a more generic InputStreamEntity to demonstrate
|
||||
|
@ -66,18 +64,12 @@ public class ClientChunkEncodedPost {
|
|||
|
||||
httppost.setEntity(reqEntity);
|
||||
|
||||
System.out.println("executing request " + httppost.getRequestLine());
|
||||
System.out.println("Executing request: " + httppost.getRequestLine());
|
||||
CloseableHttpResponse response = httpclient.execute(httppost);
|
||||
try {
|
||||
HttpEntity resEntity = response.getEntity();
|
||||
|
||||
System.out.println("----------------------------------------");
|
||||
System.out.println(response.getStatusLine());
|
||||
if (resEntity != null) {
|
||||
System.out.println("Response content length: " + resEntity.getContentLength());
|
||||
System.out.println("Chunked?: " + resEntity.isChunked());
|
||||
}
|
||||
EntityUtils.consume(resEntity);
|
||||
EntityUtils.consume(response.getEntity());
|
||||
} finally {
|
||||
response.close();
|
||||
}
|
||||
|
|
|
@ -45,15 +45,13 @@ public class ClientConnectionRelease {
|
|||
public final static void main(String[] args) throws Exception {
|
||||
CloseableHttpClient httpclient = HttpClients.createDefault();
|
||||
try {
|
||||
HttpGet httpget = new HttpGet("http://www.apache.org/");
|
||||
HttpGet httpget = new HttpGet("http://localhost/");
|
||||
|
||||
// Execute HTTP request
|
||||
System.out.println("executing request " + httpget.getURI());
|
||||
System.out.println("Executing request " + httpget.getRequestLine());
|
||||
CloseableHttpResponse response = httpclient.execute(httpget);
|
||||
try {
|
||||
System.out.println("----------------------------------------");
|
||||
System.out.println(response.getStatusLine());
|
||||
System.out.println("----------------------------------------");
|
||||
|
||||
// Get hold of the response entity
|
||||
HttpEntity entity = response.getEntity();
|
||||
|
|
|
@ -29,7 +29,6 @@ package org.apache.http.examples.client;
|
|||
|
||||
import java.util.List;
|
||||
|
||||
import org.apache.http.HttpEntity;
|
||||
import org.apache.http.client.CookieStore;
|
||||
import org.apache.http.client.methods.CloseableHttpResponse;
|
||||
import org.apache.http.client.methods.HttpGet;
|
||||
|
@ -57,29 +56,19 @@ public class ClientCustomContext {
|
|||
// Bind custom cookie store to the local context
|
||||
localContext.setCookieStore(cookieStore);
|
||||
|
||||
HttpGet httpget = new HttpGet("http://www.google.com/");
|
||||
|
||||
System.out.println("executing request " + httpget.getURI());
|
||||
HttpGet httpget = new HttpGet("http://localhost/");
|
||||
System.out.println("Executing request " + httpget.getRequestLine());
|
||||
|
||||
// Pass local context as a parameter
|
||||
CloseableHttpResponse response = httpclient.execute(httpget, localContext);
|
||||
try {
|
||||
HttpEntity entity = response.getEntity();
|
||||
|
||||
System.out.println("----------------------------------------");
|
||||
System.out.println(response.getStatusLine());
|
||||
if (entity != null) {
|
||||
System.out.println("Response content length: " + entity.getContentLength());
|
||||
}
|
||||
List<Cookie> cookies = cookieStore.getCookies();
|
||||
for (int i = 0; i < cookies.size(); i++) {
|
||||
System.out.println("Local cookie: " + cookies.get(i));
|
||||
}
|
||||
|
||||
// Consume response content
|
||||
EntityUtils.consume(entity);
|
||||
|
||||
System.out.println("----------------------------------------");
|
||||
EntityUtils.consume(response.getEntity());
|
||||
} finally {
|
||||
response.close();
|
||||
}
|
||||
|
|
|
@ -37,6 +37,7 @@ import org.apache.http.client.methods.CloseableHttpResponse;
|
|||
import org.apache.http.client.methods.HttpGet;
|
||||
import org.apache.http.conn.ssl.SSLContexts;
|
||||
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.HttpClients;
|
||||
import org.apache.http.util.EntityUtils;
|
||||
|
@ -55,11 +56,16 @@ public class ClientCustomSSL {
|
|||
} finally {
|
||||
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);
|
||||
CloseableHttpClient httpclient = HttpClients.custom()
|
||||
.setSSLSocketFactory(sslsf)
|
||||
|
|
|
@ -28,7 +28,6 @@ package org.apache.http.examples.client;
|
|||
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
import org.apache.http.HttpEntity;
|
||||
import org.apache.http.client.methods.CloseableHttpResponse;
|
||||
import org.apache.http.client.methods.HttpGet;
|
||||
import org.apache.http.conn.HttpClientConnectionManager;
|
||||
|
@ -47,14 +46,14 @@ public class ClientEvictExpiredConnections {
|
|||
PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
|
||||
cm.setMaxTotal(100);
|
||||
CloseableHttpClient httpclient = HttpClients.custom()
|
||||
.setConnectionManager(cm).build();
|
||||
.setConnectionManager(cm)
|
||||
.build();
|
||||
try {
|
||||
// create an array of URIs to perform GETs on
|
||||
String[] urisToGet = {
|
||||
"http://jakarta.apache.org/",
|
||||
"http://jakarta.apache.org/commons/",
|
||||
"http://jakarta.apache.org/commons/httpclient/",
|
||||
"http://svn.apache.org/viewvc/jakarta/httpcomponents/"
|
||||
"http://hc.apache.org/",
|
||||
"http://hc.apache.org/httpcomponents-core-ga/",
|
||||
"http://hc.apache.org/httpcomponents-client-ga/",
|
||||
};
|
||||
|
||||
IdleConnectionEvictor connEvictor = new IdleConnectionEvictor(cm);
|
||||
|
@ -64,20 +63,13 @@ public class ClientEvictExpiredConnections {
|
|||
String requestURI = urisToGet[i];
|
||||
HttpGet request = new HttpGet(requestURI);
|
||||
|
||||
System.out.println("executing request " + requestURI);
|
||||
System.out.println("Executing request " + requestURI);
|
||||
|
||||
CloseableHttpResponse response = httpclient.execute(request);
|
||||
try {
|
||||
HttpEntity entity = response.getEntity();
|
||||
|
||||
System.out.println("----------------------------------------");
|
||||
System.out.println(response.getStatusLine());
|
||||
if (entity != null) {
|
||||
System.out.println("Response content length: " + entity.getContentLength());
|
||||
}
|
||||
System.out.println("----------------------------------------");
|
||||
|
||||
EntityUtils.consume(entity);
|
||||
EntityUtils.consume(response.getEntity());
|
||||
} finally {
|
||||
response.close();
|
||||
}
|
||||
|
|
|
@ -27,8 +27,6 @@
|
|||
|
||||
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.client.config.RequestConfig;
|
||||
import org.apache.http.client.methods.CloseableHttpResponse;
|
||||
|
@ -47,29 +45,22 @@ public class ClientExecuteProxy {
|
|||
public static void main(String[] args)throws Exception {
|
||||
CloseableHttpClient httpclient = HttpClients.createDefault();
|
||||
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");
|
||||
|
||||
RequestConfig config = RequestConfig.custom().setProxy(proxy).build();
|
||||
RequestConfig config = RequestConfig.custom()
|
||||
.setProxy(proxy)
|
||||
.build();
|
||||
HttpGet request = new HttpGet("/");
|
||||
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);
|
||||
try {
|
||||
HttpEntity entity = response.getEntity();
|
||||
|
||||
System.out.println("----------------------------------------");
|
||||
System.out.println(response.getStatusLine());
|
||||
Header[] headers = response.getAllHeaders();
|
||||
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));
|
||||
}
|
||||
EntityUtils.consume(response.getEntity());
|
||||
} finally {
|
||||
response.close();
|
||||
}
|
||||
|
|
|
@ -33,8 +33,6 @@ import java.net.Proxy;
|
|||
import java.net.Socket;
|
||||
import java.net.SocketTimeoutException;
|
||||
|
||||
import org.apache.http.Header;
|
||||
import org.apache.http.HttpEntity;
|
||||
import org.apache.http.HttpHost;
|
||||
import org.apache.http.client.methods.CloseableHttpResponse;
|
||||
import org.apache.http.client.methods.HttpGet;
|
||||
|
@ -58,34 +56,26 @@ public class ClientExecuteSOCKS {
|
|||
|
||||
public static void main(String[] args)throws Exception {
|
||||
Registry<ConnectionSocketFactory> reg = RegistryBuilder.<ConnectionSocketFactory>create()
|
||||
.register("http", new MyConnectionSocketFactory())
|
||||
.build();
|
||||
.register("http", new MyConnectionSocketFactory())
|
||||
.build();
|
||||
PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(reg);
|
||||
CloseableHttpClient httpclient = HttpClients.custom().setConnectionManager(cm).build();
|
||||
CloseableHttpClient httpclient = HttpClients.custom()
|
||||
.setConnectionManager(cm)
|
||||
.build();
|
||||
try {
|
||||
InetSocketAddress socksaddr = new InetSocketAddress("mysockshost", 1234);
|
||||
HttpClientContext context = HttpClientContext.create();
|
||||
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("/");
|
||||
|
||||
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);
|
||||
try {
|
||||
HttpEntity entity = response.getEntity();
|
||||
|
||||
System.out.println("----------------------------------------");
|
||||
System.out.println(response.getStatusLine());
|
||||
Header[] headers = response.getAllHeaders();
|
||||
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));
|
||||
}
|
||||
EntityUtils.consume(response.getEntity());
|
||||
} finally {
|
||||
response.close();
|
||||
}
|
||||
|
@ -121,8 +111,7 @@ public class ClientExecuteSOCKS {
|
|||
try {
|
||||
sock.connect(remoteAddress, connectTimeout);
|
||||
} catch (SocketTimeoutException ex) {
|
||||
throw new ConnectTimeoutException("Connect to " + remoteAddress.getHostName() + "/"
|
||||
+ remoteAddress.getAddress() + " timed out");
|
||||
throw new ConnectTimeoutException(ex, host, remoteAddress.getAddress());
|
||||
}
|
||||
return sock;
|
||||
}
|
||||
|
|
|
@ -26,21 +26,18 @@
|
|||
*/
|
||||
package org.apache.http.examples.client;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.net.URI;
|
||||
import java.util.List;
|
||||
|
||||
import org.apache.http.Consts;
|
||||
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.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.impl.client.BasicCookieStore;
|
||||
import org.apache.http.impl.client.CloseableHttpClient;
|
||||
import org.apache.http.impl.client.HttpClients;
|
||||
import org.apache.http.message.BasicNameValuePair;
|
||||
import org.apache.http.util.EntityUtils;
|
||||
|
||||
/**
|
||||
|
@ -51,10 +48,11 @@ public class ClientFormLogin {
|
|||
|
||||
public static void main(String[] args) throws Exception {
|
||||
BasicCookieStore cookieStore = new BasicCookieStore();
|
||||
CloseableHttpClient httpclient = HttpClients.custom().setDefaultCookieStore(cookieStore).build();
|
||||
CloseableHttpClient httpclient = HttpClients.custom()
|
||||
.setDefaultCookieStore(cookieStore)
|
||||
.build();
|
||||
try {
|
||||
HttpGet httpget = new HttpGet("https://portal.sun.com/portal/dt");
|
||||
|
||||
HttpGet httpget = new HttpGet("https://someportal/");
|
||||
CloseableHttpResponse response1 = httpclient.execute(httpget);
|
||||
try {
|
||||
HttpEntity entity = response1.getEntity();
|
||||
|
@ -75,17 +73,12 @@ public class ClientFormLogin {
|
|||
response1.close();
|
||||
}
|
||||
|
||||
HttpPost httpost = new HttpPost("https://portal.sun.com/amserver/UI/Login?" +
|
||||
"org=self_registered_users&" +
|
||||
"goto=/portal/dt&" +
|
||||
"gotoOnFail=/portal/dt?error=true");
|
||||
List <NameValuePair> nvps = new ArrayList <NameValuePair>();
|
||||
nvps.add(new BasicNameValuePair("IDToken1", "username"));
|
||||
nvps.add(new BasicNameValuePair("IDToken2", "password"));
|
||||
|
||||
httpost.setEntity(new UrlEncodedFormEntity(nvps, Consts.UTF_8));
|
||||
|
||||
CloseableHttpResponse response2 = httpclient.execute(httpost);
|
||||
HttpUriRequest login = RequestBuilder.post()
|
||||
.setUri(new URI("https://someportal/"))
|
||||
.addParameter("IDToken1", "username")
|
||||
.addParameter("IDToken2", "password")
|
||||
.build();
|
||||
CloseableHttpResponse response2 = httpclient.execute(login);
|
||||
try {
|
||||
HttpEntity entity = response2.getEntity();
|
||||
|
||||
|
|
|
@ -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();
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
|
@ -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();
|
||||
}
|
||||
}
|
||||
}
|
|
@ -49,14 +49,15 @@ public class ClientMultiThreadedExecution {
|
|||
PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
|
||||
cm.setMaxTotal(100);
|
||||
|
||||
CloseableHttpClient httpclient = HttpClients.custom().setConnectionManager(cm).build();
|
||||
CloseableHttpClient httpclient = HttpClients.custom()
|
||||
.setConnectionManager(cm)
|
||||
.build();
|
||||
try {
|
||||
// create an array of URIs to perform GETs on
|
||||
String[] urisToGet = {
|
||||
"http://hc.apache.org/",
|
||||
"http://hc.apache.org/httpcomponents-core-ga/",
|
||||
"http://hc.apache.org/httpcomponents-client-ga/",
|
||||
"http://svn.apache.org/viewvc/httpcomponents/"
|
||||
};
|
||||
|
||||
// create a thread for each URI
|
||||
|
|
|
@ -26,7 +26,6 @@
|
|||
*/
|
||||
package org.apache.http.examples.client;
|
||||
|
||||
import org.apache.http.HttpEntity;
|
||||
import org.apache.http.HttpHost;
|
||||
import org.apache.http.auth.AuthScope;
|
||||
import org.apache.http.auth.UsernamePasswordCredentials;
|
||||
|
@ -53,10 +52,10 @@ import org.apache.http.util.EntityUtils;
|
|||
public class ClientPreemptiveBasicAuthentication {
|
||||
|
||||
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();
|
||||
credsProvider.setCredentials(
|
||||
new AuthScope(targetHost.getHostName(), targetHost.getPort()),
|
||||
new AuthScope(target.getHostName(), target.getPort()),
|
||||
new UsernamePasswordCredentials("username", "password"));
|
||||
CloseableHttpClient httpclient = HttpClients.custom()
|
||||
.setDefaultCredentialsProvider(credsProvider).build();
|
||||
|
@ -67,7 +66,7 @@ public class ClientPreemptiveBasicAuthentication {
|
|||
// Generate BASIC scheme object and add it to the local
|
||||
// auth cache
|
||||
BasicScheme basicAuth = new BasicScheme();
|
||||
authCache.put(targetHost, basicAuth);
|
||||
authCache.put(target, basicAuth);
|
||||
|
||||
// Add AuthCache to the execution context
|
||||
HttpClientContext localContext = HttpClientContext.create();
|
||||
|
@ -75,20 +74,13 @@ public class ClientPreemptiveBasicAuthentication {
|
|||
|
||||
HttpGet httpget = new HttpGet("/");
|
||||
|
||||
System.out.println("executing request: " + httpget.getRequestLine());
|
||||
System.out.println("to target: " + targetHost);
|
||||
|
||||
System.out.println("Executing request " + httpget.getRequestLine() + " to target " + target);
|
||||
for (int i = 0; i < 3; i++) {
|
||||
CloseableHttpResponse response = httpclient.execute(targetHost, httpget, localContext);
|
||||
CloseableHttpResponse response = httpclient.execute(target, httpget, localContext);
|
||||
try {
|
||||
HttpEntity entity = response.getEntity();
|
||||
|
||||
System.out.println("----------------------------------------");
|
||||
System.out.println(response.getStatusLine());
|
||||
if (entity != null) {
|
||||
System.out.println("Response content length: " + entity.getContentLength());
|
||||
}
|
||||
EntityUtils.consume(entity);
|
||||
EntityUtils.consume(response.getEntity());
|
||||
} finally {
|
||||
response.close();
|
||||
}
|
||||
|
|
|
@ -26,7 +26,6 @@
|
|||
*/
|
||||
package org.apache.http.examples.client;
|
||||
|
||||
import org.apache.http.HttpEntity;
|
||||
import org.apache.http.HttpHost;
|
||||
import org.apache.http.auth.AuthScope;
|
||||
import org.apache.http.auth.UsernamePasswordCredentials;
|
||||
|
@ -53,13 +52,14 @@ import org.apache.http.util.EntityUtils;
|
|||
public class ClientPreemptiveDigestAuthentication {
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
HttpHost targetHost = new HttpHost("localhost", 80, "http");
|
||||
HttpHost target = new HttpHost("localhost", 80, "http");
|
||||
CredentialsProvider credsProvider = new BasicCredentialsProvider();
|
||||
credsProvider.setCredentials(
|
||||
new AuthScope(targetHost.getHostName(), targetHost.getPort()),
|
||||
new AuthScope(target.getHostName(), target.getPort()),
|
||||
new UsernamePasswordCredentials("username", "password"));
|
||||
CloseableHttpClient httpclient = HttpClients.custom()
|
||||
.setDefaultCredentialsProvider(credsProvider).build();
|
||||
.setDefaultCredentialsProvider(credsProvider)
|
||||
.build();
|
||||
try {
|
||||
|
||||
// Create AuthCache instance
|
||||
|
@ -71,7 +71,7 @@ public class ClientPreemptiveDigestAuthentication {
|
|||
digestAuth.overrideParamter("realm", "some realm");
|
||||
// Suppose we already know the expected nonce value
|
||||
digestAuth.overrideParamter("nonce", "whatever");
|
||||
authCache.put(targetHost, digestAuth);
|
||||
authCache.put(target, digestAuth);
|
||||
|
||||
// Add AuthCache to the execution context
|
||||
HttpClientContext localContext = HttpClientContext.create();
|
||||
|
@ -79,20 +79,13 @@ public class ClientPreemptiveDigestAuthentication {
|
|||
|
||||
HttpGet httpget = new HttpGet("/");
|
||||
|
||||
System.out.println("executing request: " + httpget.getRequestLine());
|
||||
System.out.println("to target: " + targetHost);
|
||||
|
||||
System.out.println("Executing request " + httpget.getRequestLine() + " to target " + target);
|
||||
for (int i = 0; i < 3; i++) {
|
||||
CloseableHttpResponse response = httpclient.execute(targetHost, httpget, localContext);
|
||||
CloseableHttpResponse response = httpclient.execute(target, httpget, localContext);
|
||||
try {
|
||||
HttpEntity entity = response.getEntity();
|
||||
|
||||
System.out.println("----------------------------------------");
|
||||
System.out.println(response.getStatusLine());
|
||||
if (entity != null) {
|
||||
System.out.println("Response content length: " + entity.getContentLength());
|
||||
}
|
||||
EntityUtils.consume(entity);
|
||||
EntityUtils.consume(response.getEntity());
|
||||
} finally {
|
||||
response.close();
|
||||
}
|
||||
|
|
|
@ -26,7 +26,6 @@
|
|||
*/
|
||||
package org.apache.http.examples.client;
|
||||
|
||||
import org.apache.http.HttpEntity;
|
||||
import org.apache.http.HttpHost;
|
||||
import org.apache.http.auth.AuthScope;
|
||||
import org.apache.http.auth.UsernamePasswordCredentials;
|
||||
|
@ -53,7 +52,7 @@ public class ClientProxyAuthentication {
|
|||
CloseableHttpClient httpclient = HttpClients.custom()
|
||||
.setDefaultCredentialsProvider(credsProvider).build();
|
||||
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);
|
||||
|
||||
RequestConfig config = RequestConfig.custom()
|
||||
|
@ -62,20 +61,13 @@ public class ClientProxyAuthentication {
|
|||
HttpGet httpget = new HttpGet("/");
|
||||
httpget.setConfig(config);
|
||||
|
||||
System.out.println("executing request: " + httpget.getRequestLine());
|
||||
System.out.println("via proxy: " + proxy);
|
||||
System.out.println("to target: " + targetHost);
|
||||
System.out.println("Executing request " + httpget.getRequestLine() + " to " + target + " via " + proxy);
|
||||
|
||||
CloseableHttpResponse response = httpclient.execute(targetHost, httpget);
|
||||
CloseableHttpResponse response = httpclient.execute(target, httpget);
|
||||
try {
|
||||
HttpEntity entity = response.getEntity();
|
||||
|
||||
System.out.println("----------------------------------------");
|
||||
System.out.println(response.getStatusLine());
|
||||
if (entity != null) {
|
||||
System.out.println("Response content length: " + entity.getContentLength());
|
||||
}
|
||||
EntityUtils.consume(entity);
|
||||
EntityUtils.consume(response.getEntity());
|
||||
} finally {
|
||||
response.close();
|
||||
}
|
||||
|
|
|
@ -47,9 +47,9 @@ public class ClientWithResponseHandler {
|
|||
public final static void main(String[] args) throws Exception {
|
||||
CloseableHttpClient httpclient = HttpClients.createDefault();
|
||||
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
|
||||
ResponseHandler<String> responseHandler = new ResponseHandler<String>() {
|
||||
|
@ -69,8 +69,6 @@ public class ClientWithResponseHandler {
|
|||
String responseBody = httpclient.execute(httpget, responseHandler);
|
||||
System.out.println("----------------------------------------");
|
||||
System.out.println(responseBody);
|
||||
System.out.println("----------------------------------------");
|
||||
|
||||
} finally {
|
||||
httpclient.close();
|
||||
}
|
||||
|
|
Loading…
Reference in New Issue