`
zhangrui840121
  • 浏览: 5777 次
  • 性别: Icon_minigender_1
  • 来自: 黑龙江
最近访客 更多访客>>
社区版块
存档分类
最新评论

HttpClient 4

    博客分类:
  • http
 
阅读更多
1、HttpClient使用GET方式通过代理服务器读取页面的例子
import java.io.BufferedReader;
import java.io.InputStreamReader;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.params.ConnRoutePNames;
import org.apache.http.impl.client.DefaultHttpClient;

/**
* HttpClient使用GET方式通过代理服务器读取页面的例子。
*/
public class HttpClientGet {
	public static void main(String[] args) throws Exception {
		DefaultHttpClient httpclient = new DefaultHttpClient();
		// 访问的目标站点,端口和协议
		HttpHost targetHost = new HttpHost("www.fronware.com");
		// 代理的设置
		HttpHost proxy = new HttpHost("192.168.10.111",80);
		httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
		// 目标地址
		HttpGet httpget = new HttpGet("/");
		// 执行
		HttpResponse response = httpclient.execute(targetHost, httpget);
		HttpEntity entity = response.getEntity();
		System.out.println(response.getStatusLine());
		if (entity != null) {
			System.out.println("Response content length: " 
                       + entity.getContentLength());
		}
		// 显示结果
		BufferedReader reader = new BufferedReader(
                new InputStreamReader(entity.getContent(), "UTF-8"));
		String line = null;
		while ((line = reader.readLine()) != null) {
			System.out.println(line);
		}
		if (entity != null) {
			entity.consumeContent();
		}
	}
}


2、HttpClient 4 使用POST方式提交普通表单数据的例子
import java.io.BufferedReader;
import java.io.InputStreamReader;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.params.ConnRoutePNames;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;

/**
* HttpClient 4 使用POST方式提交普通表单数据的例子.
* 
*/
public class HttpClientPost {
	public static void main(String[] args) throws Exception {
		DefaultHttpClient httpclient = new DefaultHttpClient();
		// 代理的设置
		HttpHost proxy = new HttpHost("192.168.10.111",80);
		httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
		// 目标地址
		HttpPost httppost = new HttpPost("http://fronware.com/RestService/login");
		System.out.println("请求: " + httppost.getRequestLine());
		// 构造最简单的字符串数据
		StringEntity reqEntity = new StringEntity("username=test&password=test");
		// 设置类型
		reqEntity.setContentType("application/x-www-form-urlencoded");
		// 设置请求的数据
		httppost.setEntity(reqEntity);
		// 执行
		HttpResponse response = httpclient.execute(httppost);
		HttpEntity entity = response.getEntity();
		if (entity != null) {
			System.out.println("Response content length: " 
                         + entity.getContentLength());
		}
		// 显示结果
		BufferedReader reader = new BufferedReader(
                new InputStreamReader(entity.getContent(), "UTF-8"));
		String line = null;
		while ((line = reader.readLine()) != null) {
			System.out.println(line);
		}
		if (entity != null) {
			entity.consumeContent();
		}
	}
}


3、HttpClient 4.0通过代理访问Https的代码例子
import java.io.BufferedReader;
import java.io.InputStreamReader;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.params.ConnRoutePNames;
import org.apache.http.impl.client.DefaultHttpClient;

/**
* HttpClient 4.0通过代理访问Https的代码例子。
*/
public class HttpsProxyGet {
	public static void main(String[] args) throws Exception {
		DefaultHttpClient httpclient = new DefaultHttpClient();
		// 认证的数据
		httpclient.getCredentialsProvider().setCredentials(
                       new AuthScope("192.168.10.111", 80),
		new UsernamePasswordCredentials("username", "password"));
		// 访问的目标站点,端口和协议
		HttpHost targetHost = new HttpHost("www.google.com", 443, "https");
		// 代理的设置
		HttpHost proxy = new HttpHost("10.60.8.20", 8080);
		httpclient.getParams().setParameter(
                ConnRoutePNames.DEFAULT_PROXY, proxy);
		// 目标地址
		HttpGet httpget = new HttpGet("/adsense/login/zh_CN/?");
		// 执行
		HttpResponse response = httpclient.execute(targetHost, httpget);
		HttpEntity entity = response.getEntity();
		System.out.println(response.getStatusLine());
		if (entity != null) {
		     System.out.println("Response content length: " 
                     + entity.getContentLength());
		}
		// 显示结果
		BufferedReader reader = new BufferedReader(
                        new InputStreamReader(entity.getContent(), "UTF-8"));
		String line = null;
		while ((line = reader.readLine()) != null) {
		    System.out.println(line);
		}
		if (entity != null) {
		    entity.consumeContent();
		}
	}
}


4、HttpClient读取页面的使用例子
import java.net.Socket;
import org.apache.http.ConnectionReuseStrategy;
import org.apache.http.Header;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.HttpVersion;
import org.apache.http.impl.DefaultConnectionReuseStrategy;
import org.apache.http.impl.DefaultHttpClientConnection;
import org.apache.http.message.BasicHttpRequest;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.BasicHttpProcessor;
import org.apache.http.protocol.ExecutionContext;
import org.apache.http.protocol.HttpContext;
import org.apache.http.protocol.HttpRequestExecutor;
import org.apache.http.protocol.RequestConnControl;
import org.apache.http.protocol.RequestContent;
import org.apache.http.protocol.RequestExpectContinue;
import org.apache.http.protocol.RequestTargetHost;
import org.apache.http.protocol.RequestUserAgent;
import org.apache.http.util.EntityUtils;

/**
* HttpClient读取页面的使用例子
*/
public class HttpGet {
	public static void main(String[] args) throws Exception {

		HttpParams params = new BasicHttpParams();
		// HTTP 协议的版本,1.1/1.0/0.9
		HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
		// 字符集
		HttpProtocolParams.setContentCharset(params, "UTF-8");
		// 伪装的浏览器类型
		// IE7 是 
		// Mozilla/4.0 (compatible; MSIE 7.0b; Windows NT 6.0)

		// Firefox3.03
		// Mozilla/5.0 (Windows; U; Windows NT 5.2; zh-CN; rv:1.9.0.3) 
                   Gecko/2008092417 Firefox/3.0.3

		HttpProtocolParams.setUserAgent(params, "HttpComponents/1.1");
		HttpProtocolParams.setUseExpectContinue(params, true);

		BasicHttpProcessor httpproc = new BasicHttpProcessor();
		httpproc.addInterceptor(new RequestContent());
		httpproc.addInterceptor(new RequestTargetHost());
		httpproc.addInterceptor(new RequestConnControl());
		httpproc.addInterceptor(new RequestUserAgent());
		httpproc.addInterceptor(new RequestExpectContinue());

		HttpRequestExecutor httpexecutor = new HttpRequestExecutor();

		HttpContext context = new BasicHttpContext(null);
		//瞎写的...
		HttpHost host = new HttpHost("www.fronware.com", 80);

		DefaultHttpClientConnection conn = new DefaultHttpClientConnection();
		ConnectionReuseStrategy connStrategy = new DefaultConnectionReuseStrategy();

		context.setAttribute(ExecutionContext.HTTP_CONNECTION, conn);
		context.setAttribute(ExecutionContext.HTTP_TARGET_HOST, host);

		try {

			String[] targets = { "/", "/help.jsp" };

			for (int i = 0; i < targets.length; i++) {
				if (!conn.isOpen()) {
					Socket socket = new Socket(host.getHostName(), host.getPort());
					conn.bind(socket, params);
				}
				BasicHttpRequest request = new BasicHttpRequest("GET", targets[i]);
				System.out.println(">> Request URI: " 
                               + request.getRequestLine().getUri());

				context.setAttribute(ExecutionContext.HTTP_REQUEST, request);
				request.setParams(params);
				httpexecutor.preProcess(request, httpproc, context);
				HttpResponse response = httpexecutor.execute(request, conn, context);
				response.setParams(params);
				httpexecutor.postProcess(response, httpproc, context);

				// 返回码
				System.out.println("<< Response: " + response.getStatusLine());
				// 返回的文件头信息
				Header[] hs = response.getAllHeaders();
				for (Header h : hs) {
					System.out.println(h.getName() + ":" + h.getValue());
				}
				// 输出主体信息
				System.out.println(EntityUtils.toString(response.getEntity()));
				System.out.println("==============");
				if (!connStrategy.keepAlive(response, context)) {
					conn.close();
				} else {
				System.out.println("Connection  alive...");
				}
			}
		} finally {
		conn.close();
		}
	}
}


5、httpclient中文乱码解决
        
         httpclient默认使用ISO-8859-1读取http响应的内容,如果内容中包含汉字的话
        
         就得动用丑陋的new String(str.getBytes("ISO-8859-1"),"GBK");语句了。

         解决办法就是使用以下配置。
       
        // httpclient读取内容时使用的字符集
         private static final String CONTENT_CHARSET = "GBK";

         HttpClient client = new HttpClient();
         client.getParams().setParameter(
         HttpMethodParams.HTTP_CONTENT_CHARSET, CONTENT_CHARSET);


6、HttpClient 4处理文件上传的例子(MultipartEntity)
import java.io.File;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;

/**
* HttpClient 4处理文件上传的例子(MultipartEntity).<br>
* 需要 James Mime4j 0.5的版本,0.6的不行。
*/
public class HttpClientMultipartFormPost {
	public static void main(String[] args) throws Exception {
		HttpClient httpclient = new DefaultHttpClient();
		HttpPost httppost = new HttpPost("http://localhost");
		// 一个本地的文件
		FileBody bin = new FileBody(new File("d:/BIMG1181.JPG"));
		// 一个字符串
		StringBody comment = new StringBody("A binary file of some kind");
		// 多部分的实体
		MultipartEntity reqEntity = new MultipartEntity();
		// 增加
		reqEntity.addPart("bin", bin);
		reqEntity.addPart("comment", comment);
		// 设置
		httppost.setEntity(reqEntity);
		System.out.println("执行: " + httppost.getRequestLine());
		HttpResponse response = httpclient.execute(httppost);
		HttpEntity resEntity = response.getEntity();
		System.out.println("----------------------------------------");
		System.out.println(response.getStatusLine());
		if (resEntity != null) {
			System.out.println("返回长度: " + resEntity.getContentLength());
		}
		if (resEntity != null) {
			resEntity.consumeContent();
		}
	}
}




分享到:
评论

相关推荐

    HttpClient 3.x to HttpComponents HttpClient 4.x

    随着技术的发展,从早期的HttpClient 3.x版本迁移到更新的HttpComponents HttpClient 4.x版本是一个常见的需求。这不仅仅是一个简单的升级过程,而是涉及到对API的变化、编程模型的更新以及对网络编程的更深层次理解...

    httpclient4

    《Java HttpClient 4详解》 Java HttpClient 4,也称为Apache HttpClient 4,是Apache软件基金会开发的一个HTTP客户端实现库,用于处理与HTTP服务器的交互。这个库在Java编程环境中广泛使用,尤其对于网络请求的...

    httpClient4 最新帮助文档

    最新帮助文档通常会涵盖HttpClient 4的主要功能、用法、配置、异常处理以及最佳实践。以下是对HttpClient 4的一些关键知识点的详细解释: 1. **基本概念**: - HttpClient:HttpClient是客户端HTTP服务端点的抽象...

    httpClient4jar包

    在描述中提到的“httpclient4”,指的是HttpClient 4.x系列,这是一个稳定且广泛使用的版本。 在HttpClient 4.4.1.jar中,包含了HttpClient的主要功能实现,如HTTP方法(GET, POST等)、连接管理、重定向处理、身份...

    HttpClient 4文件上传

    ### HttpClient 4 文件上传知识点详解 #### 一、概述 在Java开发中,经常会遇到需要通过HTTP协议上传文件的需求。Apache HttpClient是一个强大的客户端HTTP组件,它不仅支持HTTP协议,还能处理HTTPS请求,并提供了...

    HttpClient 4 - 文件上传

    HttpClient 4 版本引入了许多改进,使得文件上传变得更加简单和高效。在这个主题中,我们将深入探讨HttpClient 4如何实现文件上传,以及相关的核心概念和技术。 首先,我们需要了解HttpClient 4的基本用法。...

    httpclient4中文API和使用

    首先,`httpclient4中文API.pdf`是HttpClient 4.5的中文版API文档,是学习和使用HttpClient的重要参考资料。这个文档通常会包含HttpClient的类结构、接口、方法等详细信息,以及如何使用这些API来构建HTTP请求的示例...

    Commons HTTPClient4&#46;X组件应用示例

    ### Commons HTTPClient4.X 组件应用详解 #### 一、引言 随着互联网技术的发展,越来越多的应用场景需要直接通过HTTP协议访问Web服务器上的资源。传统的做法是使用浏览器或者基于JDK提供的`java.net`包中的类如`...

    httpclient4之百度模拟登陆,回复与58同城自动登陆

    首先,我们来了解HttpClient4的基本用法。HttpClient4通过构建HTTP请求,设置请求头,如User-Agent(模拟浏览器标识),Cookie(用于保持登录状态)等,以及POST或GET参数,来模拟用户行为。在模拟登录过程中,我们...

    httpclient 4.X版本下载有的带源码包

    2013-11-21 15:31 292,890 httpclient-4.0.2.jar 2017-12-20 12:08 351,132 httpclient-4.1.1.jar 2012-08-03 01:45 451,595 httpclient-4.1.2-sources.jar 2012-08-03 01:44 352,254 httpclient-4.1.2.jar 2012-08-...

    httpclient4源码

    《深入剖析HTTPClient4源码》 HTTPClient4是Apache软件基金会开发的一个强大的HTTP客户端库,广泛应用于Java编程中,提供了高效、灵活且可扩展的HTTP通信能力。它支持多种HTTP协议版本,包括HTTP/1.1和部分HTTP/2...

    httpclient4 封装

    在这个“httpclient4 封装”中,我们将探讨HttpClient 4.2版本的使用,以及如何将它封装到自己的项目中。 HttpClient 4.2是Apache HttpClient系列的一个稳定版本,它支持HTTP/1.1和部分HTTP/2协议,提供了对HTTPS、...

    HttpClient4模拟登录回贴

    这篇博客“HttpClient4模拟登录回贴”显然探讨了如何利用HttpClient4库进行网络模拟登录以及在特定网站上发布帖子。HttpClient4适用于各种场景,如自动化测试、数据抓取等,它允许开发者构建复杂的HTTP交互逻辑。 ...

    HttpClient 4 官方教程中文翻译版

    ### HttpClient 4 官方教程中文翻译版知识点详解 #### 一、概述 Apache HttpClient 是一个用于Java应用程序的客户端HTTP组件。它旨在提供一个高效、最新且功能丰富的HTTP客户端编程框架,同时也支持HTTPS协议。...

    httpclient4中文教程.doc

    本教程将介绍HttpClient的基本概念和使用方法。 首先,HttpClient的核心功能是执行HTTP请求。通过创建HttpClient实例和指定的HTTP方法对象(如HttpGet、HttpPost等),可以向目标服务器发起请求并获取响应。以下是...

    最新android4 HTTPCLIENT4JAR包

    HTTPCLIENT4库的核心特性包括: 1. **请求与响应模型**:HTTPCLIENT4将HTTP请求和响应抽象为对象,使得开发者可以方便地构建和解析HTTP消息。例如,`HttpGet`和`HttpPost`类用于创建请求,而`HttpResponse`则封装了...

    (最新)HttpClient4模拟登录腾讯微博

    这篇最新的文章“HttpClient4模拟登录腾讯微博”探讨了如何利用HttpClient4实现对腾讯微博的模拟登录,这在自动化测试、数据抓取等场景中非常实用。 HttpClient4库提供了丰富的API,可以定制化地构造HTTP请求,包括...

    新浪,腾讯微博HttpClient4模拟登陆

    本文将深入探讨如何使用Java中的HttpClient4库来实现对新浪和腾讯微博的模拟登录。HttpClient4是一个强大的HTTP客户端库,它允许开发者执行HTTP请求并处理响应,非常适合进行网页交互。 首先,我们来看`Sina.java`...

Global site tag (gtag.js) - Google Analytics