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

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();

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: