HttpClient相关的实体类官方文档地址:http://hc.apache.org/httpcomponents-client-ga/httpclient/apidocs/

使用HttpClient发送请求、接收响应很简单,一般需要如下几步即可:
1. 创建HttpClient对象,HttpClient httpClient=new DefaultHttpClient()。
2. 创建请求方法的实例,并指定请求URL。如果需要发送GET请求,创建HttpGet对象;如果需要发送POST请求,创建HttpPost对象。
GET:
HttpGet HttpGet=new HttpGet(“http://www.baidu.com”);
httpClient.execute(httpGet);
3. 如果需要发送请求参数,可调用HttpGet、HttpPost共同的setParams(HetpParams params)方法来添加请求参数;对于HttpPost对象而言,也可调用setEntity(HttpEntity entity)方法来设置请求参数。通过一个NameValuePair集合来存放待提交的参数,并将这个参数集合传入到一个UrlEncodedFormEntity中,然后调用HttpPost的setEntity()方法将构建好的UrlEncodedFormEntity传入。
POST:
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);
4. 调用HttpClient对象的execute(HttpUriRequest request)发送请求,该方法返回一个HttpResponse。
5. 调用HttpResponse的getAllHeaders()、getHeaders(String name)等方法可获取服务器的响应头;调用HttpResponse的getEntity()方法可获取HttpEntity对象,该对象包装了服务器的响应内容。程序可通过该对象获取服务器的响应内容。
先取出服务器返回的状态码,如果等于200就说明请求和响应都成功了:
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学习笔记的更多相关文章

  1. HttpClient学习整理

    HttpClient简介HttpClient 功能介绍    1. 读取网页(HTTP/HTTPS)内容    2.使用POST方式提交数据(httpClient3)    3. 处理页面重定向    ...

  2. HttpClient 学习整理【转】

    转自 http://www.blogjava.net/Alpha/archive/2007/01/22/95216.html HttpClient 是我最近想研究的东西,以前想过的一些应用没能有很好的 ...

  3. HttpClient 学习整理 (转)

    source:http://www.blogjava.net/Alpha/archive/2007/01/22/95216.html HttpClient 是我最近想研究的东西,以前想过的一些应用没能 ...

  4. Android学习笔记之HttpClient实现Http请求....

    PS:最近光忙着考试了....破组成原理都看吐了....搞的什么也不想干...写篇博客爽爽吧....貌似明天就考试了...sad... 学习笔记: 1.如何实现Http请求来实现通信.... 2.解决 ...

  5. ASP.NET MVC Web API 学习笔记---第一个Web API程序

    http://www.cnblogs.com/qingyuan/archive/2012/10/12/2720824.html GetListAll /api/Contact GetListBySex ...

  6. WebService学习笔记系列(二)

    soap(简单对象访问协议),它是在http基础之上传递xml格式数据的协议.soap协议分为两个版本,soap1.1和soap1.2. 在学习webservice时我们有一个必备工具叫做tcpmon ...

  7. openstack学习笔记一 虚拟机启动过程代码跟踪

    openstack学习笔记一 虚拟机启动过程代码跟踪 本文主要通过对虚拟机创建过程的代码跟踪.观察虚拟机启动任务状态的变化,来透彻理解openstack各组件之间的作用过程. 当从horizon界面发 ...

  8. 多线程编程学习笔记——编写一个异步的HTTP服务器和客户端

    接上文 多线程编程学习笔记——使用异步IO 二.   编写一个异步的HTTP服务器和客户端 本节展示了如何编写一个简单的异步HTTP服务器. 1.程序代码如下. using System; using ...

  9. https学习笔记三----OpenSSL生成root CA及签发证书

    在https学习笔记二,已经弄清了数字证书的概念,组成和在https连接过程中,客户端是如何验证服务器端的证书的.这一章,主要介绍下如何使用openssl库来创建key file,以及生成root C ...

随机推荐

  1. (函数)P1149 火柴棒等式

    题解: #include<stdio.h>int a[10]={6,2,5,5,4,5,6,3,7,6};int num(int n){                          ...

  2. MJJ玩磁铁

    题目: Problem D: MJJ玩磁铁 Time Limit: 1 Sec  Memory Limit: 128 MBSubmit: 139  Solved: 9[Submit][Status][ ...

  3. PPT制作不加班的十个小窍门

    五个一键: 情景一: 上司:小万,什么字体啊这是,全部换成微软雅黑. 一键替换字体: 单击任意文本框——开始菜单栏——替换(下拉三角)——替换字体——替换为——替换.   情景二: 上司:小万,“咖啡 ...

  4. Django框架(九):视图(二) HttpRequest对象、HttpResponse对象

    1. HttpRequest对象 服务器接收到http协议的请求后,会根据报文创建HttpRequest对象,这个对象不需要我们创建,直接使用服务器构造好的对象就可以.视图的第一个参数必须是HttpR ...

  5. WebAPI异常捕捉处理,结合log4net日志(webapi框架)

    一:异常捕捉处理 首先,在我们需要区分controller的类型.是全部基层controller,还是Apicontroller.(当然一般API框架,用的都是Apicontroller).两者异常处 ...

  6. UML-领域模型-属性

    1.属性预览 2.导出属性是什么? 3.属性使用什么样的数据类型? 常见的数据类型:boolean.Date.String(Text).Integer 其他常见的:SKU.枚举类型等 而在java类中 ...

  7. python编程:从入门到实践----第六章:字典>练习

    6-1 人:使用一个字典来存储一个熟人的信息,包括名.姓.年龄和居住的城市.该字典应包含键first_name .last_name .age 和city .将存储在该字典中的每项信息都打印出来. f ...

  8. 六、Shell脚本高级编程实战第六部

    一.写一个start_nginx脚本,当启动.停止.重启时利用系统函数模拟实现系统脚本启动的特殊颜色效果 (用if实现) #!/bin/sh. /etc/init.d/functions if [ $ ...

  9. 放贷额度相关的ROI计算

    违约模型得到概率估计, 将概率值划分5档, 每一档确定一个授信系数 新的授信 = 每月收入* 授信系数 - 老的授信 计算新增授信额度 计算余额损失

  10. ZJNU 1133 - Subset sequence——中级

    推出n=1到4时,An排列的种类数分别为1 4 15 64可得(1+1)*2=4(4+1)*3=15(15+1)*4=64...故用一数列r[n]记录An的种类总数当n=3时,列举出以下15种从大到小 ...