`
rensanning
  • 浏览: 3548173 次
  • 性别: Icon_minigender_1
  • 来自: 大连
博客专栏
Efef1dba-f7dd-3931-8a61-8e1c76c3e39f
使用Titanium Mo...
浏览量:38136
Bbab2146-6e1d-3c50-acd6-c8bae29e307d
Cordova 3.x入门...
浏览量:607282
C08766e7-8a33-3f9b-9155-654af05c3484
常用Java开源Libra...
浏览量:682290
77063fb3-0ee7-3bfa-9c72-2a0234ebf83e
搭建 CentOS 6 服...
浏览量:89331
E40e5e76-1f3b-398e-b6a6-dc9cfbb38156
Spring Boot 入...
浏览量:401828
Abe39461-b089-344f-99fa-cdfbddea0e18
基于Spring Secu...
浏览量:69688
66a41a70-fdf0-3dc9-aa31-19b7e8b24672
MQTT入门
浏览量:91697
社区版块
存档分类
最新评论

Java网络通信之HttpClient

    博客分类:
  • Java
阅读更多
HttpClient 是 Apache Jakarta Common 下的子项目,可以用来提供高效的、最新的、功能丰富的支持 HTTP 协议的客户端编程工具包,并且它支持 HTTP 协议最新的版本和建议。在Android系统中内置了HttpClient。Android下可以试试Square的OkHttp

http://hc.apache.org/httpcomponents-client-ga/index.html

版本:httpclient-4.2.jar


1、基本请求
//创建一个客户端
HttpClient client = new DefaultHttpClient();

//创建一个get方法
HttpGet get = new HttpGet("http://www.baidu.com");

//执行请求
HttpResponse res = client.execute(get);

//获取协议版本・・・「HTTP/1.1」
System.out.println(res.getProtocolVersion());
//获取返回状态码・・・「200」
System.out.println(res.getStatusLine().getStatusCode());
//获取原因短语・・・「OK」
System.out.println(res.getStatusLine().getReasonPhrase());
//获取完整的StatusLine・・・「HTTP/1.1 200 OK」
System.out.println(res.getStatusLine().toString());

//获取返回头部信息
Header[] headers = res.getAllHeaders();
for (Header header : headers) {
	System.out.println(header.getName() + ": " + header.getValue());
}

//获取返回内容
if (res.getEntity() != null) {
	System.out.println(EntityUtils.toString(res.getEntity()));
}

//关闭流
EntityUtils.consume(res.getEntity());

//关闭连接
client.getConnectionManager().shutdown();


2、操作Cookie
//生成Cookie
CookieStore cookieStore = new BasicCookieStore();
BasicClientCookie stdCookie = new BasicClientCookie("name", "value");
stdCookie.setVersion(1);
stdCookie.setDomain(".baidu.com");
stdCookie.setPath("/");
stdCookie.setSecure(true);
stdCookie.setAttribute(ClientCookie.VERSION_ATTR, "1");
stdCookie.setAttribute(ClientCookie.DOMAIN_ATTR, ".baidu.com");
cookieStore.addCookie(stdCookie);

DefaultHttpClient client1 = new DefaultHttpClient();
client1.setCookieStore(cookieStore);

client1.execute(new HttpGet("http://www.baidu.com/"));

//获取Cookie
DefaultHttpClient client2 = new DefaultHttpClient();
HttpGet httpget = new HttpGet("http://www.baidu.com/");

HttpResponse res = client2.execute(httpget);

List<Cookie> cookies = client2.getCookieStore().getCookies();
for (Cookie cookie : cookies) {
	System.out.println(cookie.getName());
	System.out.println(cookie.getValue());
}

EntityUtils.consume(res.getEntity());


3、设置代理
//通过连接参数设置代理
DefaultHttpClient client1 = new DefaultHttpClient();

HttpHost proxy1 = new HttpHost("192.168.2.60", 8080, "HTTP");
client1.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy1);

HttpGet get1 = new HttpGet("http://www.facebook.com");
HttpResponse res1 = client1.execute(get1);
if (res1.getEntity() != null) {
	System.out.println(EntityUtils.toString(res1.getEntity()));
}		
EntityUtils.consume(res1.getEntity());

//设置代理认证
//client1.getCredentialsProvider().setCredentials(
//        new AuthScope("localhost", 8080),
//        new UsernamePasswordCredentials("username", "password"));


4、POST数据
//========UrlEncodedFormEntity
List<NameValuePair> formparams = new ArrayList<NameValuePair>();
formparams.add(new BasicNameValuePair("param1", "value1"));
formparams.add(new BasicNameValuePair("param2", "value2"));
UrlEncodedFormEntity entity1 = new UrlEncodedFormEntity(formparams, "UTF-8");

HttpPost post1 = new HttpPost("http://localhost/post1.do");
post1.setEntity(entity1);

new DefaultHttpClient().execute(post1);

//========FileEntity
FileEntity entity2 = new FileEntity(new File("c:\\sample.txt"));
entity2.setContentEncoding("UTF-8");

HttpPost post2 = new HttpPost("http://localhost/post2.do");
post2.setEntity(entity2);

new DefaultHttpClient().execute(post2);

//========MultipartEntity
HttpPost post3 = new HttpPost("http://localhost/post3.do");
File upfile = new File("C:\\test.jpg");
MultipartEntity entity3 = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE, null, Charset.forName("UTF-8"));
entity3.addPart("file_name",     new StringBody(upfile.getName()));
entity3.addPart("file_contents", new FileBody(upfile));
post3.setEntity(entity3);

new DefaultHttpClient().execute(post3);


5、URI构建
//方法一
URI uri1 = URIUtils.createURI("http", "www.baidu.com", -1, "/s",
		"wd=rensanning&rsv_bp=0&rsv_spt=3&inputT=1766", null);
HttpGet httpget1 = new HttpGet(uri1);

//http://www.baidu.com/s?wd=rensanning&rsv_bp=0&rsv_spt=3&inputT=1766
System.out.println(httpget1.getURI());

//方法二
List<NameValuePair> qparams = new ArrayList<NameValuePair>();
qparams.add(new BasicNameValuePair("wd", "rensanning"));
qparams.add(new BasicNameValuePair("rsv_bp", "0"));
qparams.add(new BasicNameValuePair("rsv_spt", "3"));
qparams.add(new BasicNameValuePair("inputT", "1766"));

URI uri2 = URIUtils.createURI("http", "www.baidu.com", -1, "/s",
		URLEncodedUtils.format(qparams, "UTF-8"), null);
HttpGet httpget2 = new HttpGet(uri2);

//http://www.baidu.com/s?wd=rensanning&rsv_bp=0&rsv_spt=3&inputT=1766
System.out.println(httpget2.getURI());


6、使用Scheme
DefaultHttpClient  httpclient = new DefaultHttpClient();

//========将Scheme设置到client中
SSLSocketFactory socketFactory = SSLSocketFactory.getSocketFactory();

Scheme httpsScheme = new Scheme("https", 443, socketFactory);
httpclient.getConnectionManager().getSchemeRegistry().register(httpsScheme);

HttpGet httpget = new HttpGet("https://xxx.xxx.xxx");
HttpResponse res =  httpclient.execute(httpget);

System.out.println(EntityUtils.toString(res.getEntity()));

//========使用证书做SSL连接
KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
FileInputStream fis = new FileInputStream("c:\\aa.keystore");
try {
	keyStore.load(fis, "password".toCharArray());
} finally {
	fis.close();
}

@SuppressWarnings("unused")
SSLSocketFactory socketFactory2 = new SSLSocketFactory(keyStore);
//......


7、认证
//========BASIC认证
DefaultHttpClient httpclient1 = new DefaultHttpClient();

UsernamePasswordCredentials creds1 = new UsernamePasswordCredentials("userid", "password");
AuthScope auth1 = new AuthScope("localhost", 80);

httpclient1.getCredentialsProvider().setCredentials(auth1, creds1);

HttpGet httpget1 = new HttpGet("http://localhost/auth1");

@SuppressWarnings("unused")
HttpResponse res1 =  httpclient1.execute(httpget1);

//========BASIC认证(HttpContext)
DefaultHttpClient httpclient2 = new DefaultHttpClient();

UsernamePasswordCredentials creds2 = new UsernamePasswordCredentials("admin", "admin");
AuthScope auth2 = new AuthScope("localhost", 80);

httpclient2.getCredentialsProvider().setCredentials(auth2, creds2);

HttpHost targetHost2 = new HttpHost("localhost", 80, "http");

AuthCache authCache = new BasicAuthCache();
BasicScheme basicAuth = new BasicScheme();
authCache.put(targetHost2, basicAuth);

BasicHttpContext localcontext2 = new BasicHttpContext();
localcontext2.setAttribute(ClientContext.AUTH_CACHE, authCache);

HttpGet httpget2 = new HttpGet("http://localhost/auth2");

@SuppressWarnings("unused")
HttpResponse res2 =  httpclient2.execute(httpget2, localcontext2);

//========DIGEST认证
DefaultHttpClient httpclient3 = new DefaultHttpClient();

UsernamePasswordCredentials creds3 = new UsernamePasswordCredentials("admin", "admin");
AuthScope auth3 = new AuthScope("localhost", 80);

httpclient3.getCredentialsProvider().setCredentials(auth3, creds3);

HttpHost targetHost3 = new HttpHost("localhost", 80, "http");

AuthCache authCache3 = new BasicAuthCache();
DigestScheme digestAuth = new DigestScheme();
digestAuth.overrideParamter("realm", "some realm");
digestAuth.overrideParamter("nonce", "whatever");
authCache3.put(targetHost3, digestAuth);

BasicHttpContext localcontext3 = new BasicHttpContext();
localcontext3.setAttribute(ClientContext.AUTH_CACHE, authCache3);

HttpGet httpget3 = new HttpGet("http://localhost/auth3");

@SuppressWarnings("unused")
HttpResponse res3 =  httpclient2.execute(httpget3, localcontext3);

//========NTLM认证
DefaultHttpClient httpclient4 = new DefaultHttpClient();

NTCredentials creds4 = new NTCredentials("user", "pwd", "myworkstation", "microsoft.com");

httpclient4.getCredentialsProvider().setCredentials(AuthScope.ANY, creds4);

HttpHost targetHost4 = new HttpHost("hostname", 80, "http");

HttpContext localcontext4 = new BasicHttpContext();

HttpGet httpget4 = new HttpGet("http://localhost/auth4");

@SuppressWarnings("unused")
HttpResponse res4 = httpclient3.execute(targetHost4, httpget4, localcontext4);


8、连接池
SchemeRegistry schemeRegistry = new SchemeRegistry();
schemeRegistry.register(new Scheme("http", 80, PlainSocketFactory.getSocketFactory()));
schemeRegistry.register(new Scheme("https", 443, SSLSocketFactory.getSocketFactory()));

PoolingClientConnectionManager cm = new PoolingClientConnectionManager(schemeRegistry);
//设置连接最大数
cm.setMaxTotal(200);
//设置每个Route的连接最大数
cm.setDefaultMaxPerRoute(20);
//设置指定域的连接最大数
HttpHost localhost = new HttpHost("locahost", 80);
cm.setMaxPerRoute(new HttpRoute(localhost), 50);

HttpGet httpget = new HttpGet("http://localhost/pool");

HttpClient client = new DefaultHttpClient(cm);

@SuppressWarnings("unused")
HttpResponse res = client.execute(httpget);


分享到:
评论
3 楼 yahier 2014-04-27  
  一直在用它 不过一直在用一点点功能
2 楼 为了吃方便面 2014-03-20  
赞一个
1 楼 java_bigniu 2012-11-19  

相关推荐

    JAVA利用HttpClient进行HTTPS接口调用

    接下来,`HttpClientUtil.java`文件可能是实现HttpClient工具类,提供一个静态方法来创建和初始化HttpClient实例。这个方法可能包含以下步骤: 1. 创建一个CloseableHttpClient实例,通常使用HttpClientBuilder构建...

    Java HttpClient 全部的jar包

    它是HttpClient进行网络通信的基础。 7. `httpmime-4.x.x.jar`: 这个库扩展了HttpClient,支持MIME类型的HTTP请求,如上传文件、处理多部分表单数据等。 8. `log4j-1.2.x.jar`: 这是一个日志记录框架,通常与...

    Java中Httpclient需要的jar包(httpclient.jar,httpcore.jar及commons-logging.jar)

    在Java编程中,Apache HttpClient库是一个非常重要的工具,它提供了丰富的功能来执行HTTP请求,包括GET、POST等方法。...在实际项目中,确保正确导入这些依赖并合理使用,将有助于构建高效、可靠的网络通信模块。

    java使用HttpClient通过url下载文件到本地

    对于网络编程,HttpClient是一个高效且灵活的选择。 2. **Eclipse环境配置**: 在Eclipse中使用HttpClient,首先需要将相关的jar包添加到项目的类路径中。这些jar包通常包括`httpclient`, `httpcore`, `httpmime`...

    Java-HttpClient帮助文档

    Java HttpClient是Apache软件基金会的Apache HTTP Components项目中的一个核心组件,它提供了一个强大的、高度可定制的客户端HTTP通信API。这个工具广泛应用于Java开发者中,用于执行HTTP请求,获取响应,处理各种...

    HttpClient包及例子

    总之,HttpClient是Java开发中一个强大的工具,它极大地简化了HTTP通信的实现,让开发者可以专注于业务逻辑,而不是底层的网络通信细节。无论你是新手还是经验丰富的开发者,HttpClient都能帮助你更高效地完成HTTP...

    java 访问 wcf 示例(使用的HttpClient)

    Java访问WCF服务是跨平台通信的一个典型场景,其中WCF(Windows Communication Foundation)是微软提供的一个用于构建、部署和管理服务的框架。本示例将重点讲解如何使用Java的HttpClient库来调用WCF服务。 一、WCF...

    网络通信(2HttpClient

    【网络通信(2)——HttpClient】讲解 网络通信在Android应用开发中扮演着至关重要的角色,而HttpClient作为Apache开源组织提供的一个强大工具,为开发者提供了更便捷的方式去处理与Web服务器之间的交互。...

    java 网络及通信

    本篇文章将深入探讨Java中的网络通信机制,包括标准Java接口、Apache HttpClient、Socket通信以及Android平台上的网络接口等内容。 #### 二、标准Java接口 Java标准库提供了`java.net.*`包,该包包含了用于网络...

    httpclient-4.5.3中文版文档,很实用

    HttpClient 4.5.3是该库的一个稳定版本,具有许多改进和修复,使得它在处理网络通信时更加高效和可靠。 HttpClient的主要功能包括: 1. **HTTP/1.1和HTTP/2支持**:HttpClient 4.5.3支持HTTP协议的最新版本,可以...

    JavaHttpClient

    Java HttpClient 是一个强大的网络通信库,它允许Java开发者在应用程序中实现HTTP和HTTPS协议的请求。这个工具类在电商开发中特别有用,因为通常需要与各种Web服务进行交互,如商品信息抓取、订单同步、用户反馈处理...

    JavaHttpClient实例

    本实例将深入探讨如何在Java中使用HttpClient进行网络通信。 首先,你需要在项目中引入HttpClient的相关依赖。如果是Maven项目,可以在pom.xml文件中添加以下依赖: ```xml &lt;groupId&gt;org.apache.httpcomponents ...

    commons-httpclient-3.0.jar JAVA中使用HttpClient可以用到

    总结,`commons-httpclient-3.0.jar`在JAVA中的应用,不仅提供了一种简单易用的HTTP客户端实现,还具有丰富的特性和扩展性,对于理解和实现网络通信具有重要的学习价值。然而,随着技术的进步,开发者应关注并适时...

    JAVA网络通信系统的研究与开发.zip

    Java网络通信系统是基于Java平台实现的用于在网络间交换数据的软件系统。它涉及到网络编程的基本概念、协议、设计模式以及具体的实现技术。在“JAVA网络通信系统的研究与开发”项目中,我们可以深入探讨以下几个核心...

    java爬虫所需的httpclient.rar_java HTTPCLIENT包

    在Java编程中,HttpClient常被用于网页爬虫的开发,因为它提供了对网络通信的低级别控制,使我们能够灵活地处理各种网络任务。 在使用Java HttpClient进行网页抓取时,首先需要理解以下关键概念和组件: 1. **...

    使用HttpClient必须的jar包

    HttpClient依赖HttpCore来处理底层的网络通信。 3. **HTTP协议支持**:HttpClient支持HTTP/1.1和部分HTTP/2协议。它能够处理各种HTTP方法,如GET、POST、PUT、DELETE等,并支持HTTP头的设置和处理。 4. **连接管理...

    httpClient调用wcf

    3. **HttpClient调用**:在Java端,引入HttpClient库及相关依赖(如本例中的`httpclient-4.2.3.jar`等)。使用HttpClient,你可以创建一个`HttpClient`实例,然后构建`HttpGet`或`HttpPost`对象,设置请求URL(对应...

    java_httpclient

    1. **NIO(非阻塞I/O)**:提供基于Java NIO的网络连接,支持高并发和低延迟通信。 2. **HttpTransport**:定义了HTTP传输的基本操作,如打开和关闭连接,发送请求,接收响应等。 3. **HttpClientConnection**:...

    (正式)Java之JUnit, Log4J, Ant, HttpClient, ApacheCommons

    【标题】中的知识点主要涉及Java开发中常用的四个库和一个构建工具,它们分别是JUnit、Log4J、Ant、HttpClient和Apache Commons。这些组件在Java软件开发中起着至关重要的作用。 1. JUnit:JUnit是Java编程语言的一...

Global site tag (gtag.js) - Google Analytics