您的位置:首页 > 理论基础 > 计算机网络

java HttpURLConnection下载服务器上的文件

2012-12-07 16:15 561 查看
String str="http://127.0.0.1:8080/httpFile/test.txt";

System.out.println("urlstr---->"+str);

try {

URL url = new URL(str);

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

connection.setRequestMethod("POST");

connection.setRequestProperty("Charset","UTF-8");

connection.connect();

int file_leng = connection.getContentLength();

System.out.println("file length---->"+file_leng);

BufferedInputStream bin = new BufferedInputStream(connection.getInputStream());

String path=Environment.getExternalStorageDirectory()+"/eBook/inw/"+bookName+".inw";

File file = new File(path);

if(!file.getParentFile().exists()){

file.getParentFile().mkdirs();

}

OutputStream out=new FileOutputStream(file);

int size=0;

int len=0;

byte[] buf = new byte[1024];

while((size=bin.read(buf))!=-1){

len+=size;

out.write(buf,0,1024);

/* android 中为了更新进度条

Message msg = handler.obtainMessage();

msg.arg1=len*100/file_leng;

handler.sendMessage(msg);

*/

Thread.sleep(1000);

System.out.println("下载了: "+len*100/file_leng+"%\n");

}

bin.close();

out.close();

} catch (MalformedURLException e) {

// TODO Auto-generated catch block

e.printStackTrace();

} catch (IOException e) {

// TODO Auto-generated catch block

e.printStackTrace();

} catch (InterruptedException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: