android系统提供了url通信,Android两种HTTP通信,HttpURLConnection和HttpClient

Android系统中主要提供了两种方式来进行HTTP通信,HttpURLConnection和HttpClient,几乎在任何项目的代码中我们都能看到这两个类的身影,使用率非常高。

不过HttpURLConnection和HttpClient的用法还是稍微有些复杂的,如果不进行适当封装的话,很容易就会写出不少重复代码。于是乎,一些Android网络通信框架也就应运而生,比如说AsyncHttpClient,它把HTTP所有的通信细节全部封装在了内部,我们只需要简单调用几行代码就可以完成通信操作了。再比如Universal-Image-Loader,它使得在界面上显示网络图片的操作变得极度简单,开发者不用关心如何从网络上获取图片,也不用关心开启线程、回收图片资源等细节,Universal-Image-Loader已经把一切都做好了。这里简单介绍下HttpURLConnection和HttpClient的使用。至于框架后面会研究后,再介绍

HttpClient的get使用

HttpClient mClient; //http客户端

public static HttpEntity getEntity(String uri,ArrayList params,int method) throws    ClientProtocolException, IOException{

mClient=new DefaultHttpClient();

HttpUriRequest request=null;

switch (method) {

case HTTP_GET://get请求

StringBuilder sb=new StringBuilder(uri);

//判断设置参数为不为空

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

sb.append("?");

//设置配置参数

for (BasicNameValuePair param : params) {

sb.append(param.getName()).append("=")

.append(URLEncoder.encode(param.getValue(), "utf-8")).append("&");

}

sb.deleteCharAt(sb.length()-1);    //删除多余的 &

}

HttpGet get=new HttpGet(sb.toString());    //发送get请求

request=get;

break;

}

//cookie缓存

HttpClientParams.setCookiePolicy(mClient.getParams(), CookiePolicy.BROWSER_COMPATIBILITY);

//连接时间

mClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 5000);

//设置请求超时时间

mClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 5000);

//执行请求 获得响应

HttpResponse response = mClient.execute(request);

if(response.getStatusLine().getStatusCode()==200){    //如果成功 返回HttpEntity 对象

return response.getEntity();

}

return null;

}

HttpURLConnection的post使用 post是 表单方式请求的

URL url =new URL(actionUrl);

HttpURLConnection con=(HttpURLConnection)url.openConnection();

con.setReadTimeout(10 * 1000);        //读数请求时间

con.setConnectTimeout(10 * 1000);    //连接超时

/* 允许Input、Output,不使用Cache */

con.setDoInput(true);    //以后就可以使用conn.getInputStream().read();

con.setDoOutput(true);    //以后就可以使用conn.getOutputStream().write()  get用不到这个

con.setUseCaches(false);    //不使用缓存

/* 设置传送的method=POST */

con.setRequestMethod("POST");

/* setRequestProperty */

con.setRequestProperty("Connection", "Keep-Alive");    //保持tcp连接

con.setRequestProperty("Charset", "UTF-8");            //传输字符格式 UTF-8

con.setRequestProperty("Content-Type",

"multipart/form-data;boundary="+boundary);

/* 设置DataOutputStream */

DataOutputStream ds =

new DataOutputStream(con.getOutputStream());

ds.writeBytes(twoHyphens + boundary + end);

ds.writeBytes("Content-Disposition: form-data; "+

"name=\"file1\";filename=\""+

newName +"\""+ end);

ds.writeBytes(end);

/* 取得文件的FileInputStream */

FileInputStream fStream =new FileInputStream(uploadFile);

/* 设置每次写入1024bytes */

int bufferSize =1024;

byte[] buffer =new byte[bufferSize];

int length =-1;

/* 从文件读取数据至缓冲区 */

while((length = fStream.read(buffer)) !=-1)

{

/* 将资料写入DataOutputStream中 */

ds.write(buffer, 0, length);

}

ds.writeBytes(end);

ds.writeBytes(twoHyphens + boundary + twoHyphens + end);

/* close streams */

fStream.close();

ds.flush();

/* 取得Response内容 */

InputStream is = con.getInputStream();

int ch;

StringBuffer b =new StringBuffer();

while( ( ch = is.read() ) !=-1 )

{

b.append( (char)ch );

}

/* 将Response显示于Dialog */

showDialog("上传成功"+b.toString().trim());

/* 关闭DataOutputStream */

ds.close();

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值