您的位置:首页 > 理论基础 > 计算机网络

【HttpClient4.5中文教程】【第一章 :基础】1.1执行请求(一)

2015-07-29 18:05 591 查看

第一章 :基础

1.1执行请求

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

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

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

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包含了一个协议名称,主机名,可选端口,资源路径,可选的参数,可选的片段。

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


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

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>
输出:

http://www.google.com/search?q=httpclient&btnG=Google+Search&aq=f&oq=


1.1.2.HTTP 响应(Response)

HTTP 相应是服务器接收并解析请求信息后返回给客户端的信息,它的起始行包含了一个协议版本,一个状态码和描述状态的短语。

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


1.1.3.处理报文首部(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"

HttpClient也提供了其他便利的方法吧HTTP报文转化为单个的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]);
     }
}


输出:

c1 = a

path=/

domain=localhost

c2 = b

path=/

c3 = c

domain=localhost


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

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

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

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

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

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

其他内容请查看目录贴点击打开链接
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: