HttpClient学习笔记
HttpClient相关的实体类官方文档地址:http://hc.apache.org/httpcomponents-client-ga/httpclient/apidocs/
HttpGet HttpGet=new HttpGet(“http://www.baidu.com”);
httpClient.execute(httpGet);
HttpPost httpPost=new HttpPost(“http://www.baidu.com”);
List<NameValuePair>params=newArrayList<NameValuePair>();
Params.add(new BasicNameValuePair(“username”,”admin”));
Params.add(new BasicNameValuePair(“password”,”123456”));
UrlEncodedFormEntity entity=newUrlEncodedFormEntity(params,”utf-8”);
httpPost.setEntity(entity);
HttpClient.execute(HttpPost);
If(httpResponse.getStatusLine().getStatusCode()==200){
//请求和响应都成功了
HttpEntityentity=HttpResponse.getEntity();//调用getEntity()方法获取到一个HttpEntity实例
//用EntityUtils.toString()这个静态方法将HttpEntity转换成字符串,防止服务器返回的数据带有中文,所以在转换的时候将字符集指定成utf-8就可以了
Stringresponse=EntityUtils.toString(entity,”utf-8”);
}
6. 释放连接。无论执行方法是否成功,都必须释放连接。
GET请求示例代码:
public static String HttpGet(String url) {
// 关闭HttpClient系统日志;
System.setProperty("org.apache.commons.logging.Log","org.apache.commons.logging.impl.SimpleLog");
System.setProperty("org.apache.commons.logging.simplelog.showdatetime","true");
System.setProperty("org.apache.commons.logging.simplelog.log.org.apache.commons.httpclient","stdout");
HttpClient httpClient = new DefaultHttpClient();
HttpGet get = new HttpGet(url);
HttpResponse response = null;
HttpEntity httpEntity = null;
String content = null;
try {
response = httpClient.execute(get);
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
//判断gzip,解压缩
if(!ObjectUtil.isEmpty(response.getLastHeader("Content-Encoding")) && (response.getLastHeader("Content-Encoding").toString()).indexOf("gzip")>=0){
response.setEntity(new GzipDecompressingEntity(response.getEntity()));
}
httpEntity = response.getEntity();
content = EntityUtils.toString(httpEntity);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (null != httpEntity) {
try {
httpEntity.consumeContent();//已经弃用
} catch (IOException e) {
e.printStackTrace();
}
}
}
return content;
}
POST请求示例代码:
/**
* @param url
* @param data (以流的方式发送请求参数)
* @return
*/
public static String HttpPost(String url, String data) {
// 关闭HttpClient系统日志;
System.setProperty("org.apache.commons.logging.Log","org.apache.commons.logging.impl.SimpleLog");
System.setProperty("org.apache.commons.logging.simplelog.showdatetime","true");
System.setProperty("org.apache.commons.logging.simplelog.log.org.apache.commons.httpclient","stdout"); HttpClient httpClient = new DefaultHttpClient();
HttpPost post = new HttpPost(url);
HttpResponse response = null;
HttpEntity httpEntity = null;
String content = null;
try {
StringEntity entity = new StringEntity(data,"UTF-8");
post.setEntity(entity);
response = httpClient.execute(post);
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
httpEntity = response.getEntity();
content = EntityUtils.toString(httpEntity,"UTF-8");
}
} catch (Exception e) {
Logger.getRootLogger().error("HttpPost-流的方式:" + e.getMessage());
} finally {
if (null != httpEntity) {
try {
httpEntity.consumeContent();
} catch (IOException e) {
Logger.getRootLogger().error("HttpPost-流的方式:" + e.getMessage());
}
}
}
return content;
}
释放连接注意的问题:
上述示例中使用的httpEntity.consumeContent()自从4.1版本就已经废弃,不建议使用了,建议使用InputStream.close() on the input stream returned bygetContent()来完成。官方sample如下:
CloseableHttpClient httpclient = HttpClients.createDefault();
try {
HttpGet httpget = new HttpGet("http://www.apache.org/");
// Execute HTTP request
CloseableHttpResponse response = httpclient.execute(httpget);
try {
// Get hold of the response entity
HttpEntity entity = response.getEntity();
// If the response does not enclose an entity, there is no need
// to bother about connection release
if (entity != null) {
InputStream instream = entity.getContent();//获取流对象
try {
instream.read();
// do something useful with the response
} catch (IOException ex) {
// In case of an IOException the connection will be released
// back to the connection manager automatically
throw ex;
} finally {
// Closing the input stream will trigger connection release
instream.close();
}
}
} finally {
response.close();
}
} finally {
httpclient.close();
}
也可以使用EntityUtils.consume(entity); Ensures that the entity content is fully consumed and the content stream, if exists, is closed.
官方建议使用这种方法:
@Deprecated
void consumeContent()
throws IOException
Deprecated. (4.1) Use EntityUtils.consume(HttpEntity)
This method is deprecated since version 4.1. Please use standard java convention to ensure resource deallocation by calling InputStream.close() on the input stream returned by getContent()
This method is called to indicate that the content of this entity is no longer required. All entity implementations are expected to release all allocated resources as a result of this method invocation. Content streaming entities are also expected to dispose
of the remaining content, if any. Wrapping entities should delegate this call to the wrapped entity.
This method is of particular importance for entities being received from a connection. The entity needs to be consumed completely in order to re-use the connection with keep-alive.
Throws:
IOException - if an I/O error occurs.
See Also:
and #writeTo(OutputStream)
HttpClient学习笔记的更多相关文章
- HttpClient学习整理
HttpClient简介HttpClient 功能介绍 1. 读取网页(HTTP/HTTPS)内容 2.使用POST方式提交数据(httpClient3) 3. 处理页面重定向 ...
- HttpClient 学习整理【转】
转自 http://www.blogjava.net/Alpha/archive/2007/01/22/95216.html HttpClient 是我最近想研究的东西,以前想过的一些应用没能有很好的 ...
- HttpClient 学习整理 (转)
source:http://www.blogjava.net/Alpha/archive/2007/01/22/95216.html HttpClient 是我最近想研究的东西,以前想过的一些应用没能 ...
- Android学习笔记之HttpClient实现Http请求....
PS:最近光忙着考试了....破组成原理都看吐了....搞的什么也不想干...写篇博客爽爽吧....貌似明天就考试了...sad... 学习笔记: 1.如何实现Http请求来实现通信.... 2.解决 ...
- ASP.NET MVC Web API 学习笔记---第一个Web API程序
http://www.cnblogs.com/qingyuan/archive/2012/10/12/2720824.html GetListAll /api/Contact GetListBySex ...
- WebService学习笔记系列(二)
soap(简单对象访问协议),它是在http基础之上传递xml格式数据的协议.soap协议分为两个版本,soap1.1和soap1.2. 在学习webservice时我们有一个必备工具叫做tcpmon ...
- openstack学习笔记一 虚拟机启动过程代码跟踪
openstack学习笔记一 虚拟机启动过程代码跟踪 本文主要通过对虚拟机创建过程的代码跟踪.观察虚拟机启动任务状态的变化,来透彻理解openstack各组件之间的作用过程. 当从horizon界面发 ...
- 多线程编程学习笔记——编写一个异步的HTTP服务器和客户端
接上文 多线程编程学习笔记——使用异步IO 二. 编写一个异步的HTTP服务器和客户端 本节展示了如何编写一个简单的异步HTTP服务器. 1.程序代码如下. using System; using ...
- https学习笔记三----OpenSSL生成root CA及签发证书
在https学习笔记二,已经弄清了数字证书的概念,组成和在https连接过程中,客户端是如何验证服务器端的证书的.这一章,主要介绍下如何使用openssl库来创建key file,以及生成root C ...
随机推荐
- mysql的常见面试问题
1.如何登陆mysql数据库 MySQL -u username -p 2.如何开启/关闭mysql服务 service mysql start/stop 3.查看mysql的状态 service m ...
- 深入分析Java反射(四)-动态代理
动态代理的简介 Java动态代理机制的出现,使得Java开发人员不用手工编写代理类,只要简单地指定一组接口及委托类对象,便能动态地获得代理类.代理类会负责将所有的方法调用分派到委托对象上反射执行,在分 ...
- Cutting Sticks UVA - 10003(DP 仍有不明白的地方)
题意:对一根长为l的木棒进行切割,给出n个切割点,每次切割的价值,等于需要切割的木头长度. 一开始理解错了,认为切割点时根据当前木条的左端点往右推算. 实际上,左端点始终是不变的一直是0,右端点一直是 ...
- 884A. Book Reading#抽空学习好孩子(模拟)
题目出处:http://codeforces.com/problemset/problem/884/A 题目大意:每天时间分两部分,工作和学习,工作优先,闲暇读书,问第几天读完 #include< ...
- spring启动,spring mvc ,要不要xml配置,基于注解配置
老项目是09-11年搞的,用的是spring+struts2,没有用注解,全xml配置.web.xml中也配置了一大堆. 现在启动新项目,在项目中用spring+springmvc ,主要用注解,也用 ...
- 让几个横向排列的浮动子div居中显示的方法
div设置成float之后,就无法使子div居中显示了,那么如何让几个横向排列的浮动的div居中显示呢,下面有个不错的方法,希望对大家有所帮助 div设置成float之后,在父div中设置text-a ...
- 2019ICPC 上海网络赛 L. Digit sum(二维树状数组+区间求和)
https://nanti.jisuanke.com/t/41422 题目大意: 给出n和b,求1到n,各数在b进制下各位数之和的总和. 直接暴力模拟,TLE.. 没想到是要打表...还是太菜了. # ...
- spring前两天
1,Spring是什么 (1) Spring是JavaEE 一站式,轻量级 容器框架 ① JavaEE :企业级 ② 一站式: JavaWeb开发的三层 直接使用Spring一个框架全部完成 ③ 轻量 ...
- MACOSX下查看某个端口被哪个程序占用及杀进程方法
sudo lsof -i :9000 COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME java 61342 a 313u IPv6 0x11111 ...
- shell的集合运算
用cat,sort,uniq命令实现文件行的交集 .并集.补集 交集 $F_1 \cap F_2 $ cat f1 f2 | sort | uniq -d 并集 $F_1 \cup F_2 $ cat ...