1.普通java代码
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
public class FileDownloadFromUrl {
public static File downloadFile(String urlPath,String downloadDir) {
File file = null;
try {
// 统一资源
URL url = new URL(urlPath);
// 连接类的父类,抽象类
URLConnection urlConnection = url.openConnection();
// http的连接类
HttpURLConnection httpURLConnection = (HttpURLConnection) urlConnection;
//设置请求方法
httpURLConnection.setRequestMethod("POST");
//设置字符编码
httpURLConnection.setRequestProperty("Charset", "utf-8");
// 打开到此 URL引用的资源的通信链接(如果尚未建立这样的连接)。
httpURLConnection.connect();
int fileLength = httpURLConnection.getContentLength();
System.out.println("file length:" + fileLength);
URL urlString = httpURLConnection.getURL();
System.out.println(urlString);
String fileFullName = urlString.toString().substring(urlString.toString().lastIndexOf("/"));
BufferedInputStream bin = new BufferedInputStream(httpURLConnection.getInputStream());
String path = downloadDir + fileFullName;
System.out.println(path);
file = new File(path);
if(!file.getParentFile().exists()) {
file.getParentFile().mkdirs();
}
OutputStream out = new FileOutputStream(file);
int size = 0;
byte[] buf = new byte[1024];
while ((size = bin.read(buf)) != -1) {
out.write(buf, 0, size);
}
bin.close();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
return file;
}
public static void main(String[] args) {
downloadFile("http://p1.so.qhimgs1.com/t01fb2e1eae98cfb781.jpg", "e:/logs1/logs2");
}
}
2.servlet版
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String urlPath = "http://p1.so.qhimgs1.com/t01fb2e1eae98cfb781.jpg";
try {
// 统一资源
URL url = new URL(urlPath);
// 连接类的父类,抽象类
URLConnection urlConnection = url.openConnection();
// http的连接类
HttpURLConnection httpURLConnection = (HttpURLConnection) urlConnection;
//设置请求方法
httpURLConnection.setRequestMethod("POST");
//设置字符编码
httpURLConnection.setRequestProperty("Charset", "utf-8");
// 打开到此 URL引用的资源的通信链接(如果尚未建立这样的连接)。
httpURLConnection.connect();
String fileName = httpURLConnection.getURL().getFile().replace("/", "");
fileName = new String(fileName.getBytes(),"ISO-8859-1");
response.setContentType("application/octet-stream;charset=ISO-8859-1");
response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
response.addHeader("Pargam", "no-cache");
response.addHeader("Cache-Control", "no-cache");
OutputStream out = response.getOutputStream();
InputStream read = httpURLConnection.getInputStream();
BufferedInputStream in = new BufferedInputStream(read);
int size = 0;
byte[] buf = new byte[10240];
while ((size = in.read(buf)) != -1) {
out.write(buf, 0, size);
}
in.close();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}