httpclient4.5 入门教程 1.1执行请求

本文转载自http://blog.csdn.net/u011179993/article/details/47131773

第一章 :基础

1.1执行请求

HttpClient最基本的功能是执行HTTP方法,一个 HTTP 方法的执行包含一个或多个 HTTP 请求/HTTP 相应的交换,通常由 HttpClient的内部来处理。使用者被要求提供一个Request对象来执行,HttpClient就会把请求传送给目标服务器并返回一个相对应的response对象,如果执行不成功,将会抛出一个异常。

显然,HttpClient API 的主要切入点就是定义描述上述契约的HttpClient接口。

一个简单的请求执行事例:

  1. CloseableHttpClient httpclient = HttpClients.createDefault();  
  2. HttpGet httpget = new HttpGet(“http://localhost/”);  
  3. CloseableHttpResponse response = httpclient.execute(httpget);  
  4. try {  
  5.    <…>  
  6. finally {  
  7.    response.close();  
  8. }  
CloseableHttpClient httpclient = HttpClients.createDefault();
HttpGet httpget = new HttpGet("http://localhost/");
CloseableHttpResponse response = httpclient.execute(httpget);
try {
   <...>
} finally {
   response.close();
}

1.1.1. HTTP 请求(Request)

所有 HTTP 请求都有一个请求起始行,这个起始行由方法名,请求 URI 和 HTTP 协议版本组成。HttpClient很好地支持了HTTP/1.1规范中所有的HTTP方法:GET,HEAD, POST,PUT, DELETE, TRACE 和 OPTIONS。每个方法都有一个特别的类:HttpGet,HttpHead, HttpPost,HttpPut,HttpDelete,HttpTrace和HttpOptions。URI是统一资源标识符的缩写,用来标识与请求相符合的资源。HTTP 请求URI包含了一个协议名称,主机名,可选端口,资源路径,可选的参数,可选的片段。

  1. HttpGet httpget = new HttpGet(  
  2.      ”http://www.google.com/search?hl=en&q=httpclient&btnG=Google+Search&aq=f&oq=”);  
HttpGet httpget = new HttpGet(
     "http://www.google.com/search?hl=en&q=httpclient&btnG=Google+Search&aq=f&oq=");

HttpClient提供了URIBuilder工具类来简化创建、修改请求 URIs。

  1. URI uri = new URIBuilder()  
  2.           .setScheme(”http”)  
  3.           .setHost(”www.google.com”)  
  4.           .setPath(”/search”)  
  5.           .setParameter(”q”“httpclient”)  
  6.           .setParameter(”btnG”“Google Search”)  
  7.           .setParameter(”aq”“f”)  
  8.           .setParameter(”oq”“”)  
  9.           .build();  
  10. HttpGet httpget = new HttpGet(uri);  
  11. System.out.println(httpget.getURI());</span>  
URI uri = new URIBuilder()
          .setScheme("http")
          .setHost("www.google.com")
          .setPath("/search")
          .setParameter("q", "httpclient")
          .setParameter("btnG", "Google Search")
          .setParameter("aq", "f")
          .setParameter("oq", "")
          .build();
HttpGet httpget = new HttpGet(uri);
System.out.println(httpget.getURI());</span>
输出:
  1. http://www.google.com/search?q=httpclient&btnG=Google+Search&aq=f&oq=  
http://www.google.com/search?q=httpclient&btnG=Google+Search&aq=f&oq=


1.1.2.HTTP 响应(Response)

HTTP 相应是服务器接收并解析请求信息后返回给客户端的信息,它的起始行包含了一个协议版本,一个状态码和描述状态的短语。
  1. HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1  
  2.                              ,HttpStatus.SC_OK, ”OK”);  
  3. System.out.println(response.getProtocolVersion());  
  4. System.out.println(response.getStatusLine().getStatusCode());  
  5. System.out.println(response.getStatusLine().getReasonPhrase());  
  6. System.out.println(response.getStatusLine().toString());  
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());

输出:
  1. HTTP/1.1  
  2. 200  
  3. OK  
  4. HTTP/1.1 200 OK  
HTTP/1.1
200
OK
HTTP/1.1 200 OK


1.1.3.处理报文首部(Headers)

一个HTTP报文包含了许多描述报文的首部,比如内容长度,内容类型等。HttpClient提供了一些方法来取出,添加,移除,枚举首部。

  1. HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1,HttpStatus.SC_OK, “OK”);  
  2. response.addHeader(”Set-Cookie”,“c1=a; path=/; domain=localhost”);  
  3. response.addHeader(”Set-Cookie”,“c2=b; path=\”/\”, c3=c; domain=\”localhost\”“);  
  4. Header h1 = response.getFirstHeader(”Set-Cookie”);  
  5. System.out.println(h1);  
  6. Header h2 = response.getLastHeader(”Set-Cookie”);  
  7. System.out.println(h2);  
  8. Header[] hs = response.getHeaders(”Set-Cookie”);  
  9. System.out.println(hs.length);  
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接口

  1. HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1,HttpStatus.SC_OK, “OK”);  
  2. response.addHeader(”Set-Cookie”,“c1=a; path=/; domain=localhost”);  
  3. response.addHeader(”Set-Cookie”,“c2=b; path=\”/\”, c3=c; domain=\”localhost\”“);  
  4. HeaderIterator it = response.headerIterator(”Set-Cookie”);  
  5. while (it.hasNext()) {  
  6.      System.out.println(it.next());  
  7. }  
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”


HttpClient也提供了其他便利的方法吧HTTP报文转化为单个的HTTP元素。

  1. HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1,HttpStatus.SC_OK, “OK”);  
  2. response.addHeader(”Set-Cookie”,“c1=a; path=/; domain=localhost”);  
  3. response.addHeader(”Set-Cookie”,“c2=b; path=\”/\”, c3=c; domain=\”localhost\”“);  
  4. HeaderElementIterator it = new BasicHeaderElementIterator(  
  5. response.headerIterator(”Set-Cookie”));  
  6. while (it.hasNext()) {  
  7.      HeaderElement elem = it.nextElement();  
  8.      System.out.println(elem.getName() + ” = ” + elem.getValue());  
  9.      NameValuePair[] params = elem.getParameters();  
  10.      for (int i = 0; i < params.length; i++) {  
  11.           System.out.println(” ” + params[i]);  
  12.      }  
  13. }  
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]);
     }
}

输出:
c1 = a
path=/
domain=localhost
c2 = b
path=/
c3 = c
domain=localhost


======================================总结区域(非原文)============================

1.对于HttpClient你可以把它简单理解成浏览器就好了。

2.HttpClient请求是必不可少的,所以构建请求很重要,要对HTTP报文有一定的了解。

3.响应不是必须的,因为HttpClient是客户端编程,只是为了方便测试使用。

4.学会处理首部很重要,会面有更加详细的内容。

5.对HTTP协议不是很了解的同学,推荐看《HTTP权威指南》这本书。


其他内容请查看目录贴点击打开链接


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值