Android 中的两种请求网络资源的方式:HttpClient和HttpURLConnection
2015-09-13 18:55
876 查看
第一种:HttpURLConnection
//创建请求路径
(1):URL url=new URL(String path);
//获取链接
(2):HttpURLConnection conn=(HttpURLConnection)url.openConnection();
//设置请求方式
(3):conn.setRequestMethod("GET");
//设置请求超长时间
(4):conn.setReadTimeout(3000);
//设置可以进行流的操作
(5):conn.setDoInput(true);conn.setDoOutput(true);
//获取请求码,判断请求状态
(6):int code=conn.getResponseCode();
//获取对应的流
InputStream in=conn.getInputStream();
OutputStream=conn.getOutputStream();
第二种:HttpClient
//创建请求路径
(1):URI url=new URI(String path);
//创建一个客户端的HttpClient
(2):HttpClient cont=new DefaultHttpClient();
//设置get请求方式
(3):HttpGet get=new HttpGet(url);
//用HttpClient客户端请求对象发送get请求,返回一个请求回复
(4):HttpResponse response=cont.execute(get);
//获取请求的回复状态
(5):HttpEntity enity=response.getEntity();
//判断请求的状态
if(enity!=null){//请求成功
//获取流
(6):InpuStream in=enity.getContent();
OutputStream out=enity.getContent();
}
//创建请求路径
(1):URL url=new URL(String path);
//获取链接
(2):HttpURLConnection conn=(HttpURLConnection)url.openConnection();
//设置请求方式
(3):conn.setRequestMethod("GET");
//设置请求超长时间
(4):conn.setReadTimeout(3000);
//设置可以进行流的操作
(5):conn.setDoInput(true);conn.setDoOutput(true);
//获取请求码,判断请求状态
(6):int code=conn.getResponseCode();
//获取对应的流
InputStream in=conn.getInputStream();
OutputStream=conn.getOutputStream();
第二种:HttpClient
//创建请求路径
(1):URI url=new URI(String path);
//创建一个客户端的HttpClient
(2):HttpClient cont=new DefaultHttpClient();
//设置get请求方式
(3):HttpGet get=new HttpGet(url);
//用HttpClient客户端请求对象发送get请求,返回一个请求回复
(4):HttpResponse response=cont.execute(get);
//获取请求的回复状态
(5):HttpEntity enity=response.getEntity();
//判断请求的状态
if(enity!=null){//请求成功
//获取流
(6):InpuStream in=enity.getContent();
OutputStream out=enity.getContent();
}
相关文章推荐
- HDU 5439. Aggregated Counting (2015长春网络赛C题)
- 2015长春网络赛1003 HDU 5439 Aggregated Counting
- 长春网络赛 travel hdu5441
- HTTP状态码
- Python设定ftplib,httplib,urllib等的timeout值
- http://www.aboutyun.com/thread-8792-1-1.html
- 2015长春网络赛 1007 - The Water Problem(裸线段树)
- boost库asio详解8——几个TCP的简单例
- 2015长春网络赛1001 - HDU5433 - Alisha’s Party (模拟)
- http://www.aboutyun.com/thread-6551-1-1.html
- 2015长春网络赛1003(hdu5439)推公式
- 《Unix网络编程》读书笔记
- 【网络】(六)TCP的十一种状态
- Java网络编程 UDP发送与接收数据
- Unix网络编程中的I/O模型
- [PHP学习教程 - 网络]002.获取网页内容(URL Content)
- http-关于application/x-www-form-urlencoded等字符编码的解释说明
- 与三菱Q系列PLC-TCP通信(MC协议)学习总结
- Java网络编程 获取本地主机名称和地址
- HDU 5446 Unknown Treasure (2015年长春赛区网络赛J题)