网络下载-HttpClient

来源:互联网 发布:淮安java培训机构 编辑:程序博客网 时间:2024/05/29 16:21
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