Request-URI是用来标识申请请求资源的(UniformResource Identifier)标识符。HTTP请求URI包括:aprotocol scheme(协议方案),host name(主机名),optional port,(端口)resourcepath(资源路径),optional query, and optional fragment.
HttpGethttpget = new HttpGet(
“http://www.google.com/search?hl=en&q=httpclient&btnG=Google+Search&aq=f&oq=”);
HttpClient提供URIBuilder功能类来简化创建和修改请求URI的过程。
URIuri = new URIBuilder()
.setScheme(“http”)
.setHost(“www.google.com”)
.setPath("/search")
.setParameter(“q”,“httpclient”)
.setParameter(“btnG”,“Google Search”)
.setParameter(“aq”,“f”)
.setParameter(“oq”,"")
.build();
HttpGethttpget = new HttpGet(uri);
System.out.println(httpget.getURI());
输出>
http://www.google.com/search?q=httpclient&btnG=Google+Search&aq=f&oq=
1.1.2HTTP应答
HTTP应答是指服务器收到或解释了客户端发送的信息后返回的消息。这个消息的首行包括:状态码、协议版本和相关的文本短语。
HttpResponseresponse = 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.1200 OK
1.1.3消息头操作
HTTP消息包含一些消息头的描述属性,如内容长度、内容类型等等。HttpClient提供了关于头的恢复、添加、移除和枚举方法。
HttpResponseresponse = 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\”");
Headerh1 = response.getFirstHeader(“Set-Cookie”);
System.out.println(h1);
Headerh2 = 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接口
HttpResponseresponse = 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\”");
HeaderIteratorit = response.headerIterator(“Set-Cookie”);
while(it.hasNext()) {
System.out.println(it.next());
}
输出&g