网络下载-HttpClient

apache的包,用着很爽。厚实的基础库。


// HttpClient get请求
DefaultHttpClient client = new DefaultHttpClient();
HttpGet get = new HttpGet("http://192.168.1.29:8080/itheima83/servlet/LoginServlet?username=abcdef&pwd=123456");


BasicHttpResponse response = (BasicHttpResponse) client.execute(get);
int status = response.getStatusLine().getStatusCode();
if(status == 200){
	InputStream is = response.getEntity().getContent();
	ByteArrayOutputStream bos = new ByteArrayOutputStream();
	byte[] buffer = new byte[1024*10];
	int len =0;
	while((len = is.read(buffer)) != -1){
		bos.write(buffer,0,len);
	}
	message = bos.toString();
	bos.close();
	is.close();
}






// HttpClient post请求
DefaultHttpClient client = new DefaultHttpClient();
//HttpGet get = new HttpGet("http://192.168.1.29:8080/itheima83/servlet/LoginServlet?username=abcdef&pwd=123456");
HttpPost post = new HttpPost("http://192.168.1.29:8080/itheima83/servlet/LoginServlet");
//设置请求体
List<BasicNameValuePair> list = new ArrayList<BasicNameValuePair>();
BasicNameValuePair value1 = new BasicNameValuePair("username","abcdef");
BasicNameValuePair value2 = new BasicNameValuePair("pwd","123456");
list.add(value1);
list.add(value2);
UrlEncodedFormEntity myentity;
myentity = new UrlEncodedFormEntity(list);
post.setEntity(myentity);




BasicHttpResponse response = (BasicHttpResponse) client.execute(post);
int status = response.getStatusLine().getStatusCode();
if(status == 200){
InputStream is = response.getEntity().getContent();
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] buffer = new byte[1024*10];
int len =0;
while((len = is.read(buffer)) != -1){
bos.write(buffer,0,len);
}
message = bos.toString();
bos.close();
is.close();
}




// post 文件上传(这个库,下载容易,上传难。因为请求体的封装类好像没有)
//android 自带的 apche库。没有最新的上传请求体包装类。
MultipartEntity ;
需要加入新版本的HttpClient的库jar,才能使用组件上传
// 各个版本,支持上传的类相当不同. 在jar 库里有。android 自带的。
测试 HttpClient4.1.3,不需要依赖库。最新到4.5.1。
HttpPost post = new HttpPost("http://192.168.1.29:8080/mytry/Upload");
File file = new File("/data/data/com.hunty.upanddown/files/wo.java");
//可以加入多个 FileBody
FileBody body = new FileBody(file);
MultipartEntity myentity = new MultipartEntity();
myentity.addPart("zhangjianqiu.png", body);
post.setEntity(myentity);






// post 下载
InputStream is = response.getEntity().getContent();
FileOutputStream bos = new FileOutputStream("/data/data/com.hunty.upanddown/files/zhangjianqiu.png");
byte[] buffer = new byte[1024*10];
int len =0;
while((len = is.read(buffer)) != -1){
bos.write(buffer,0,len);
}
bos.close();
获得的实体,转型封装成别的对象 FileEntity或者InputStreamEntity失败。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值