1.建立连接
HttpClient httpclient = new DefaultHttpClient();
2.创建存放路径
Environment.getExternalStorageDirectory();
String saveDir =sdCardDir.getCanonicalPath() +"/DownFile";
File file1 = new File(saveDir);
if(!file1.exists()){
file1.mkdir();
}
3.选择传值方法(post或者get)
HttpPost httpRequest = new HttpPost(url);
HttpResponse response = httpclient.execute(httpRequest);
HttpEntity entity = response.getEntity();
BufferedHttpEntity bufHttpEntity = new BufferedHttpEntity(entity);
InputStream is = bufHttpEntity.getContent();
FileOutputStream out = new FileOutputStream(saveDir,false);
bufferedOutputStream = new BufferedOutputStream(
out);
bufferedInputStream = new BufferedInputStream(
is);
byte[] buf = new byte[4096];
int bytesRead = 0;
while (bytesRead >= 0) {
long now = System.currentTimeMillis();
bufferedOutputStream.write(buf, 0, bytesRead);
bytesRead = bufferedInputStream.read(buf);
}
bufferedOutputStream.flush();
4.关闭流及httpclient
bufferedOutputStream.close();
out.close();
if(bufferedOutputStream!=null){
bufferedOutputStream.close();
}
if(out!=null){
out.close();
}
if(bufferedInputStream!=null){
bufferedInputStream.close();
}
if(is!=null){
is.close();
}
shutdownHttpClient();
private void shutdownHttpClient() {
if (httpclient != null && httpclient.getConnectionManager() != null) {
httpclient.getConnectionManager().shutdown();
}
}
posted on 2013-05-08 20:30
Terry Zou 阅读(691)
评论(0) 编辑 收藏 所属分类:
Android