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

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 网络及通信

    java网络及通信、httpClient、socket通信、HttpURLConnection、java 中常用的几种网络通信方式。在此总结、希望对需要的同仁有所帮助。

    HttpClient jar包

    Java网络通信中HttpClient的全部Jar包!!很齐全 希望对大家有帮助!!

    httpclient4_中文版帮助文档.

    httpclient4 中文版帮助文档,最新官方版翻译版 前言 超文本传输协议(HTTP)也许是当今互联网上使用的最重要的协议了。Web服务,有网络功能的设备和网络计算的发展,都持续扩展了HTTP协议的角色,超越了用户使用的...

    JAVA上百实例源码以及开源项目

     Java局域网通信——飞鸽传书源代码,大家都知道VB版、VC版还有Delphi版的飞鸽传书软件,但是Java版的确实不多,因此这个Java文件传输实例不可错过,Java网络编程技能的提升很有帮助。 Java聊天程序,包括服务端和...

    JAVA上百实例源码以及开源项目源代码

     Java局域网通信——飞鸽传书源代码,大家都知道VB版、VC版还有Delphi版的飞鸽传书软件,但是Java版的确实不多,因此这个Java文件传输实例不可错过,Java网络编程技能的提升很有帮助。 Java聊天程序,包括服务端和...

    commons-httpclient-3.0-rc1.jar

    HttpClient 是Apache Jakarta Common 下的子项目,可以用来提供高效的、最新的、功能丰富的支持 HTTP 协议的客户端编程工具包,并且它支持 HTTP 协议最新的版本和建议。

    Java网络爬虫小说下载器。.zip

    Java网络爬虫小说下载器。使用httpclient,jsoup,dom4j,json-lib,SWT创建的可下载小说的网络爬虫项目。 软件开发设计:应用软件开发、系统软件开发、移动应用开发、网站开发C++、Java、python、web、C#等语言的...

    java开源包4

    PortGroper 是一款java写的开源拒绝服务测试工具,它不是僵尸网络类的ddos,而是使用大量的代理作为bots发起DDOS。Port Groper可以与用测试防火墙,干扰web 统计脚本的跟踪,为网站增加流量..往好了用什么都能干,就是...

    java开源包101

    PortGroper 是一款java写的开源拒绝服务测试工具,它不是僵尸网络类的ddos,而是使用大量的代理作为bots发起DDOS。Port Groper可以与用测试防火墙,干扰web 统计脚本的跟踪,为网站增加流量..往好了用什么都能干,就是...

    java开源包11

    PortGroper 是一款java写的开源拒绝服务测试工具,它不是僵尸网络类的ddos,而是使用大量的代理作为bots发起DDOS。Port Groper可以与用测试防火墙,干扰web 统计脚本的跟踪,为网站增加流量..往好了用什么都能干,就是...

    java开源包6

    PortGroper 是一款java写的开源拒绝服务测试工具,它不是僵尸网络类的ddos,而是使用大量的代理作为bots发起DDOS。Port Groper可以与用测试防火墙,干扰web 统计脚本的跟踪,为网站增加流量..往好了用什么都能干,就是...

    java开源包9

    PortGroper 是一款java写的开源拒绝服务测试工具,它不是僵尸网络类的ddos,而是使用大量的代理作为bots发起DDOS。Port Groper可以与用测试防火墙,干扰web 统计脚本的跟踪,为网站增加流量..往好了用什么都能干,就是...

    java开源包8

    PortGroper 是一款java写的开源拒绝服务测试工具,它不是僵尸网络类的ddos,而是使用大量的代理作为bots发起DDOS。Port Groper可以与用测试防火墙,干扰web 统计脚本的跟踪,为网站增加流量..往好了用什么都能干,就是...

    java开源包10

    PortGroper 是一款java写的开源拒绝服务测试工具,它不是僵尸网络类的ddos,而是使用大量的代理作为bots发起DDOS。Port Groper可以与用测试防火墙,干扰web 统计脚本的跟踪,为网站增加流量..往好了用什么都能干,就是...

    java开源包5

    PortGroper 是一款java写的开源拒绝服务测试工具,它不是僵尸网络类的ddos,而是使用大量的代理作为bots发起DDOS。Port Groper可以与用测试防火墙,干扰web 统计脚本的跟踪,为网站增加流量..往好了用什么都能干,就是...

    java jdk实列宝典 光盘源代码

    12反射 是java程序开发的特征之一,允许java程序对自身进行检查,并能直接操作程序的内部属性; instanceof操作符,instanceof.java; 获取类的信息,ViewClassInfoJrame.java; 动态调用类的方法,CallMetod.java; ...

    java开源包3

    PortGroper 是一款java写的开源拒绝服务测试工具,它不是僵尸网络类的ddos,而是使用大量的代理作为bots发起DDOS。Port Groper可以与用测试防火墙,干扰web 统计脚本的跟踪,为网站增加流量..往好了用什么都能干,就是...

    java开源包1

    PortGroper 是一款java写的开源拒绝服务测试工具,它不是僵尸网络类的ddos,而是使用大量的代理作为bots发起DDOS。Port Groper可以与用测试防火墙,干扰web 统计脚本的跟踪,为网站增加流量..往好了用什么都能干,就是...

    android http通信demo

    android 当中涉及到网络编程的部分经常会用到http通信,同时android也为我么您...前面提到的HttpUrlConnection接口是java当中的通信接口,而HttpClient则是java当中自带的通信接口。这个demo就实现了这四种通信方式。

Global site tag (gtag.js) - Google Analytics