HttpUrlConnection下载文件

<div class="iteye-blog-content-contain" style="font-size: 14px"></div>
根据已有的来下载文件

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class Connection {
public void DownloadFile(){
/*定义文件地址*/ String urlpath = "http://img3.duitang.com/uploads/item/201511/13/20151113090806_vEMCX.gif";
try{
URL url = new URL(urlpath);
/*链接打开*/ HttpURLConnection conn=(HttpURLConnection) url.openConnection();
conn.setRequestProperty("Charset","UTF-8");
if(conn.getResponseCode()==conn.HTTP_OK)
{
System.out.println("服务器连接成功");
InputStream is = new BufferedInputStream(conn.getInputStream());
int i = urlpath.lastIndexOf("/");
String filename=urlpath.substring(i+1);
OutputStream outputFile = new FileOutputStream("E:\\downloadtest\\"+filename);
byte b[] = new byte[1024];
int len = 0;
while((len=is.read(b))!=-1)
{
outputFile.write(b, 0, len);

}
outputFile.flush();
System.out.println("下载成功");
}
}catch(ArithmeticException e){

} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

public static void main(String[] args) {
Connection sb = new Connection();
sb.DownloadFile();
}
}

猜你喜欢

转载自lwg524961040.iteye.com/blog/2382498