HttpClient请求
HttpClient支持HTTP/1.1这个版本定义的所有Http方法:GET,HEAD,POST,PUT,DELETE,TRACE和OPTIONS。对于每一种http方法,HttpClient都定义了一个相应的类:HttpGet,HttpHead,HttpPost,HttpPut,HttpDelete,HttpTrace和HttpOpquertions。
Httpclient还可以自定义uri,方法如下:
//http://www.baidu.com/ur/chengjiu?from=super
URI uri = new URIBuilder()
.setScheme("http")
.setHost("www.baidu.com")
.setPath("/ur/chengjiu")
.setParameter("from", "super")
.build();
HttpGet httpget = new HttpGet(uri);
System.out.println(httpget.getURI());
输出:http://www.baidu.com/ur/chengjiu?from=super
下面模仿一个简单的请求例子:
HttpClient httpclient =HttpClients.createDefault();
HttpResponse response = httpclient.execute(httpget);
消息回应
消息头
Response中包含了回应的消息,我们可以轻易的得到回应的消息,方法如下
//得到回应状态码
System.out.println(response.getProtocolVersion());
System.out.println(response.getStatusLine().getStatusCode());
System.out.println(response.getStatusLine().getReasonPhrase());
System.out.println(response.getStatusLine().toString());
//得到回应消息头,HeaderIterator是参数迭代器
HeaderIterator it =response.headerIterator();
while (it.hasNext()) {
System.out.println(it.next());
}
消息实体
得到实体内容
HttpEntity entity =response.getEntity();
if (entity != null) {
try {
InputStream content=entity.getContent();
String charset=EntityUtils.getContentCharSet(entity);
BufferedReader reader=new BufferedReader(new InputStreamReader(content,charset));
String line=null;
while((line = reader.readLine()) != null){
System.out.println(line);
}
reader.close();
} catch (Exception e) {
}
}
模拟表单登陆
很多应用程序需要模拟提交Html表单的过程,举个例子,登陆一个网站或者将输入内容提交给服务器。HttpClient提供了UrlEncodedFormEntity这个类来帮助实现这一过程。
List<NameValuePair>formparams = new ArrayList<NameValuePair>();
formparams.add(new BasicNameValuePair("email", "value1"));
formparams.add(new BasicNameValuePair("password", "value2"));
HttpPost httppost = new HttpPost("http://www.renren.com/PLogin.do");
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams, Consts.UTF_8);
httppost.setEntity(entity);
httpclient.execute(httppost);