没有合适的资源?快使用搜索试试~ 我知道了~
HttpClient 学习资料
4星 · 超过85%的资源 需积分: 10 10 下载量 196 浏览量
2011-09-23
09:16:00
上传
评论
收藏 499KB PDF 举报
温馨提示
试读
37页
简单的对HTTPCLIENT中一些常用类做了介绍,对刚入门的朋友可以有很大帮助。
资源推荐
资源详情
资源评论
1 / 37
HttpClient-4.0.1 官方教程
HttpClient 不是一个浏览器,它是一个客户端 HTTP 传输类库。HttpClient 作用是传输和接收 HTTP 消息。
HttpClient 不尝试缓存内容,执行内嵌 HTML 页面中的 javascript 脚本,尝试猜测内容类型,重新定义请求/重定
向 URI 位置,其他功能与 HTTP 传输无关。
第一章 Fundamentals(基础)
1.1 执行请求
HttpClient 最重要的功能是执行 HTTP 方法。执行一个 HTTP 方法涉及一个或多个 HTTP 请求/ HTTP 响应信息
交流,通常是由 HttpClient 内部处理。用户提供一个请求对象,HttpClient 发送请求到目标服务器,希望服务
器返回一个相应的响应对象,或者抛出一个异常(如果执行失败)。
很自然,该 HttpClient API 的主要切入点是 HttpClient 的接口定义。
下面是一个请求执行过程中的最简单形式的例子:
HttpClient httpclient = new DefaultHttpClient();
HttpGet httpget = new HttpGet("http://localhost/");
HttpResponse response = httpclient.execute(httpget);
HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream instream = entity.getContent();
int l;
byte[] tmp = new byte[2048];
while ((l = instream.read(tmp)) != -1) {
// „..
}
}
1.1.1 HTTP Request (HTTP 请求)
所有的 HTTP 请求有一个请求行包含一个方法名,请求 URI 和 HTTP 协议版本。
HttpClient 支持在 HTTP/1.1 规范中定义的所有 HTTP 方法:GET、HEAD、POST、PUT、 DELETE,、TRACE and
OPTIONS,用一些特殊的类来表示每一个方法:HttpGet、HttpHead、 HttpPost、 HttpPut、 HttpDelete、 HttpTrace
和 HttpOptions。
HTTP 请求 URI 的包括协议、主机名、可选的端口、资源的路径、可选的查询和可选的片段。
HttpGet httpget = new HttpGet(
"http://www.google.com/search?hl=en&q=httpclient&btnG=Google+Search&aq=f&oq=");
2 / 37
HttpClient 提供了一个实用的方法来简化创建和修改请求的 URIs,URI 可以由程序编程组装:
URI uri = URIUtils.createURI("http", "www.google.com", -1, "/search",
"q=httpclient&btnG=Google+Search&aq=f&oq=", null);
HttpGet httpget = new HttpGet(uri);
System.out.println(httpget.getURI());
输出:
http://www.google.com/search?q=httpclient&btnG=Google+Search&aq=f&oq=
查询字符串也可以从各个参数生成:
List<NameValuePair> qparams = new ArrayList<NameValuePair>();
qparams.add(new BasicNameValuePair("q", "httpclient"));
qparams.add(new BasicNameValuePair("btnG", "Google Search"));
qparams.add(new BasicNameValuePair("aq", "f"));
qparams.add(new BasicNameValuePair("oq", null));
URI uri = URIUtils.createURI("http", "www.google.com", -1, "/search",
URLEncodedUtils.format(qparams, "UTF-8"), null);
HttpGet httpget = new HttpGet(uri);
System.out.println(httpget.getURI());
输出:
http://www.google.com/search?q=httpclient&btnG=Google+Search&aq=f&oq=
1.1.2 HTTP Response (HTTP 响应)
HTTP Response 消息是由服务器发送回客户端,客户端接收并解释的请求消息。该消息的第一行由协议版本、
数字状态码和相关的简短文本构成。
HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, "OK");
System.out.println(response.getProtocolVersion());
System.out.println(response.getStatusLine().getStatusCode());
System.out.println(response.getStatusLine().getReasonPhrase());
System.out.println(response.getStatusLine().toString());
输出:
HTTP/1.1
200
OK
HTTP/1.1 200 OK
3 / 37
1.1.3 Working with message headers (处理头部消息)
HTTP 信息可以包含一系列头部描述消息的属性,例如:内容长度,内容类型等等。HttpClient 提供方法检
索、添加、删除、列举头部信息。
HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, "OK");
response.addHeader("Set-Cookie", "c1=a; path=/; domain=localhost");
response.addHeader("Set-Cookie", "c2=b; path=\"/\", c3=c; domain=\"localhost\"");
Header h1 = response.getFirstHeader("Set-Cookie");
System.out.println(h1);
Header h2 = response.getLastHeader("Set-Cookie");
System.out.println(h2);
Header[] hs = response.getHeaders("Set-Cookie");
System.out.println(hs.length);
输出:
Set-Cookie: c1=a; path=/; domain=localhost
Set-Cookie: c2=b; path="/", c3=c; domain="localhost"
2
最有效的方法来获得给定类型的所有头部信息是利用 HeaderIterator 接口。
HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, "OK");
response.addHeader("Set-Cookie", "c1=a; path=/; domain=localhost");
response.addHeader("Set-Cookie", "c2=b; path=\"/\", c3=c; domain=\"localhost\"");
HeaderIterator it = response.headerIterator("Set-Cookie");
while (it.hasNext()) {
System.out.println(it.next());
}
输出:
Set-Cookie: c1=a; path=/; domain=localhost
Set-Cookie: c2=b; path="/", c3=c; domain="localhost"
它还提供了便利的方法把 HTTP 消息解析成单独的头部信息元素。
HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, "OK");
response.addHeader("Set-Cookie", "c1=a; path=/; domain=localhost");
response.addHeader("Set-Cookie", "c2=b; path=\"/\", c3=c; domain=\"localhost\"");
HeaderElementIterator it = new BasicHeaderElementIterator(response.headerIterator("Set-Cookie"));
while (it.hasNext()) {
HeaderElement elem = it.nextElement();
System.out.println(elem.getName() + " = " + elem.getValue());
NameValuePair[] params = elem.getParameters();
for (int i = 0; i < params.length; i++) {
System.out.println(" " + params[i]);
4 / 37
}
}
输出:
c1 = a
path=/
domain=localhost
c2 = b
path=/
c3 = c
domain=localhost
1.1.4 HTTP entity (HTTP 实体)
HTTP 消息能传输内容实体的请求或响应,在一些请求和响应中可以发现实体,因为它们是可选的。HTTP 规
范定义了两个实体包装的方法:POST 和 PUT,响应通常附上内容实体。
HttpClient 根据内容来源区分了三种不同类型的实体:
Streamed:内容是从流接收或产生的,特别是,这类实体是从 HTTP 响应中接收,流媒体通常是不可重
复的。
self-contained:内容是在内存中或者从独立的一个连接或其它实体中获得,self-contained 实体通
常是重复的。
wrapping:内容从另一个实体获得。
1.1.4.1 Repeatable entities (可重复的实体)
一个实体可以是可重复的,这意味着它的内容可以被读取一次以上。这是唯一可能有自我包含的实体(像
ByteArrayEntity 或 StringEntity)。
1.1.4.2 Using HTTP entities (使用 HTTP 实体)
由于一个实体即能表示二进制内容又能表示字符内容,它支持字符编码(支持后者,即:字符内容)。
从 实 体 中 读 取 内 容 , 通过 HttpEntity 的 getContent 方 法 可 以 取 回 输 入 流 , 并 返回一个
java.io.InputStream,或者给 HttpEntity 的 writeTo(OutputStream) 方法提供一个输出流,它将一次性
返回所有的被写在流里的内容。
当实体已收到传入消息,HttpEntity#getContentType()和 HttpEntity#getContentLength()方
法可用于读取常见的元数据,例如内容类型和内容长度(如果可用)。由于内容类型标题可以包含文本 MIME
类型的字符编码,像 text/plain 或者 text/html,HttpEntity#getContentEncoding()方法用来读取此
信息。如果标题不可用,返回的长度为-1,并返回内容类型为 NULL,如果内容类型标题可用,返回标题对
象。
当创建一个即将卸任的消息实体,此元数据必须由实体创建者提供。
StringEntity myEntity = new StringEntity("important message", "UTF-8");
System.out.println(myEntity.getContentType());
System.out.println(myEntity.getContentLength());
System.out.println(EntityUtils.getContentCharSet(myEntity));
System.out.println(EntityUtils.toString(myEntity));
System.out.println(EntityUtils.toByteArray(myEntity).length);
5 / 37
输出:
Content-Type: text/plain; charset=UTF-8
17
UTF-8
important message
17
1.1.5 Ensuring release of low level resources (确保底层资源的释放)
当响应实体完成时,重要的是要确保所有的实体内容已被完全销毁,使该连接可以安全地返回到连接池,由
以后的请求重复利用连接管理器,最简单的方法是调用 HttpEntity#consumeContent()方法来消毁任何可用
的流内容。HttpClient 一旦检测到流的末尾的内容已经到达,就自动释放基础连接返回到连接管理器。
HttpEntity#consumeContent()方法安全的调用一次以上。调用 HttpUriRequest#abort()方法可以简单地
终止请求。
HttpGet httpget = new HttpGet("http://localhost/");
HttpResponse response = httpclient.execute(httpget);
HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream instream = entity.getContent();
int byteOne = instream.read();
int byteTwo = instream.read();
// Do not need the rest
httpget.abort();
}
该连接将不被重用,底层的资源将正确地释放。
1.1.6 Consuming entity content(销毁实体内容)
推 荐 的 方 法 消 耗 的 实 体 内 容 是 通 过 使 用 其 HttpEntity # getContent ()或 HttpEntity # writeTo
(OutputStream 中)方法。HttpClient 的还配备了 EntityUtils 类,它暴露了一些静态方法能够更容易地从一
个实体读取内容或信息。而不是直接读取 java.io.InputStream,使用这个类的方法可以取回 string/byte array
整个内容体,然而,EntityUtils 不鼓励使用,除非实体响应来自一个可信赖的 HTTP 服务器和已知的有限长度。
HttpGet httpget = new HttpGet("http://localhost/");
HttpResponse response = httpclient.execute(httpget);
HttpEntity entity = response.getEntity();
if (entity != null) {
long len = entity.getContentLength();
if (len != -1 && len < 2048) {
System.out.println(EntityUtils.toString(entity));
} else {
// Stream content out
剩余36页未读,继续阅读
资源评论
- yitongfling2012-07-13挺好的,我是初学者,不懂的还有一些,可以再上网补充
niuxl521
- 粉丝: 0
- 资源: 5
上传资源 快速赚钱
- 我的内容管理 展开
- 我的资源 快来上传第一个资源
- 我的收益 登录查看自己的收益
- 我的积分 登录查看自己的积分
- 我的C币 登录后查看C币余额
- 我的收藏
- 我的下载
- 下载帮助
安全验证
文档复制为VIP权益,开通VIP直接复制
信息提交成功