HttpURLConnection和HttpClient的使用

2013年末,刚刚开始学android开发的时候,都是使用HttpURLConnection和HttpClient来进行网络访问的,现在网上一搜索开源的网络访问框架一大堆,比如OkHttpVolleyRetrofitrxjava等等。那么HttpURLConnection和HttpClient有什么区别呢?

android支持TCP和UDP通信,但是应用程序大部分网络调用都是通过建立tcp之上的http请求完成的。android 提供了两个的http通信的API,就是apache的HttpClient和java的HttpUrlConnection,其实两种都是提供相同的功能。

HttpURLConnection是继承URLConnection的抽象类,是标准的java接口,比较轻量,使用大多数的应用程序。

使用HttpURLConnection进行http请求:

/* *  

* Get方式发送请求 

*/

public Object sendGETRequest(String path, Mapparams,String ecoding) throws Exception{

StringBuilder url = new StringBuilder(path);

url.append("?");

for (Map.Entryentry : params.entrySet()) {

url.append(entry.getKey()).append("=");

url.append(URLEncoder.encode(entry.getValue(), ecoding));

url.append("&");

}

url.deleteCharAt(url.length() - 1);

HttpURLConnection conn = (HttpURLConnection) new URL(url.toString())

.openConnection();

conn.setConnectTimeout(5000);

conn.setRequestMethod("GET");

if (conn.getResponseCode() == 200) {

String sessionid = HttpUtils.queryStringForGet(url.toString());

InputStream inStream = conn.getInputStream();

return inStream;

}

return null;

}


/* *

* POST方式发送请求

*/

public Object sendPOSTRequest(String path,Mapparams, String encoding) throws Exception {

StringBuilder data = new StringBuilder();

if (params != null && !params.isEmpty()) {

//搭建post访问路径 

for (Map.Entryentry : params.entrySet()) {

data.append(entry.getKey()).append("=");

data.append(URLEncoder.encode(entry.getValue(), encoding));

data.append("&");

}

data.deleteCharAt(data.length() - 1);

}

byte[] entity = data.toString().getBytes();

HttpURLConnection conn = (HttpURLConnection) new URL(path).openConnection();

conn.setConnectTimeout(5000);

conn.setRequestMethod("POST");

conn.setDoOutput(true);// 允许对外输出

conn.setRequestProperty("Content-Type",

"application/x-www-form-urlencoded");

conn.setRequestProperty("Content-Length", String.valueOf(entity.length));

OutputStream outputStream = conn.getOutputStream();

outputStream.write(entity);

if (conn.getResponseCode() == 200) {

InputStream inStream = conn.getInputStream();

return inStream;

}

return null;

}

HttpClient是apache公司提供的http协议库,功能比较丰富,对http进行封装和处理,所以比较难扩展。

/* 

* 通过url发送get请求,第一次请求后保存sessionID

*/

public static String queryStringForGet(String url){HttpGet httpGet = new HttpGet(url);

//实例化HttpGet对象

String result = null;

if (null!=JSPSESSID) {

//判断sessionid是否为空,不为空就将jspsessionid的值放到cookie中发送给服务器httpGet.setHeader("Cookie","JSPSESSID="+JSPSESSID);}

//实例化连接

DefaultHttpClient httpClient = new DefaultHttpClient();

try {

//实例化返回结果

HttpResponse response = httpClient.execute(httpGet);

//返回状态码为200,表示成功

if (response.getStatusLine().getStatusCode()==200) {

result = EntityUtils.toString(response.getEntity(),HTTP.UTF_8);

CookieStore mCookieStore = httpClient.getCookieStore();

//取得cookiestore

List  list = mCookieStore.getCookies();

for (int i = 0; i < list.size(); i++) {

//取得cookie的JSPSESSID的值存在静态变量中,保证每次都是同一个值

if ("JSPSESSID".equals(list.get(i).getName())) {

JSPSESSID = list.get(i).getValue();

}

}

return result;

}

} catch (ClientProtocolException e) {

e.printStackTrace();

}catch (IOException e) {

e.printStackTrace();}

return null;

}

}

public static String PATH = "http://服务器的IP地址";

public static String JSPSESSID = null;//静态变量用来保存jspsessId的值

/* 

* 通过url发送post请求,第一次请求后保存sessionID

 */

public static String queryStringForPost(String url){

HttpPost httpPost = new HttpPost(url);

//实例化HttpPost对象

String result = null;

if (null!=JSPSESSID) {

//判断sessionid是否为空,不为空就将jspsessionid的值放到cookie中发送给服务器httpPost.setHeader("Cookie","JSPSESSID="+JSPSESSID);

}

//实例化连接

DefaultHttpClient httpClient = new DefaultHttpClient();

try {

//实例化返回结果

HttpResponse response = httpClient.execute(httpPost);

//返回状态码为200,表示成功

if (response.getStatusLine().getStatusCode()==200) {

result = EntityUtils.toString(response.getEntity(),HTTP.UTF_8);

CookieStore mCookieStore = httpClient.getCookieStore();

//取得cookiestore

List list = mCookieStore.getCookies();

for (int i = 0; i < list.size(); i++) {

//取得cookie的JSPSESSID的值存在静态变量中,保证每次都是同一个值

if ("JSPSESSID".equals(list.get(i).getName())) {

JSPSESSID = list.get(i).getValue();

}

}

return result;

}

} catch (ClientProtocolException e) {

e.printStackTrace();

}catch (IOException e) {

e.printStackTrace();

}

return null;

}

不过现在的网络http请求一般都会使用开源框架,文章开头介绍的框架是现在比较流行的,大家可以使用,并且最好是能够解刨里面的实现原理,这对提高自己的能力有显著的提升。

本人第一次写技术文章,写得不好的地方希望各个大神指出来,我会改进的。顺便开通了公众号,以后的文章也会更新到公众号,还有一些生活和面试之类的分享哦。



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值