HttpClient基本操作
来源:互联网 发布:sas软件哪些人要学 编辑:程序博客网 时间:2024/05/17 03:49
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);
- HttpClient的基本操作
- HttpClient基本操作
- HttpClient 的基本操作
- HttpClient Get和post基本操作
- java HttpClient学习总结:基本http操作
- Android网络请求操作httpurlconnection和httpclient基本使用
- HttpUrlConnection+Handler 和 HttpClient+AsyncTask 实现页面的基本操作
- HttpClient的基本使用
- HttpClient基本用法
- httpclient基本用法
- Android HttpClient基本使用方法
- Android HttpClient基本使用方法
- Android HttpClient基本使用方法
- HttpClient基本使用
- Android HttpClient基本使用方法
- Android HttpClient基本使用方法
- HttpClient : 基本使用整理
- Android HttpClient基本使用方法
- nyoj145 聪明的小柯
- IP数据包长度问题总结
- HDU1535:Invitation Cards(SPFA)
- C++11特性
- Oracle装完后,计算机名改了,监听程序无法启动!
- HttpClient基本操作
- 学习kruskal
- 神器!explainshell:超级强大的Linux命令解释工具
- 数据库连接池(JSP)
- 十四、第三章再续:快速选择SELECT算法的深入分析与实现
- Spring框架总结
- JSP页面显示时出现乱码解决办法
- 在MAC系统上安装Tomcat
- 根据simhash找出集合中相似文档的算法