更新時(shí)間:2022-04-01 10:27:38 來(lái)源:動(dòng)力節(jié)點(diǎn) 瀏覽3204次
當(dāng)我們想要下載網(wǎng)站上的某個(gè)資源時(shí),我們會(huì)獲取一個(gè)url,它是服務(wù)器定位資源的一個(gè)描述,下載的過(guò)程有如下幾步:
(1)客戶(hù)端發(fā)起一個(gè)url請(qǐng)求,獲取連接對(duì)象。
(2)服務(wù)器解析url,并且將指定的資源返回一個(gè)輸入流給客戶(hù)。
(3)建立存儲(chǔ)的目錄以及保存的文件名。
(4)輸出了寫(xiě)數(shù)據(jù)。
(5)關(guān)閉輸入流和輸出流。
/**
* @功能 下載臨時(shí)素材接口
* @param filePath 文件將要保存的目錄
* @param method 請(qǐng)求方法,包括POST和GET
* @param url 請(qǐng)求的路徑
* @return
*/
public static File saveUrlAs(String url,String filePath,String method){
//System.out.println("fileName---->"+filePath);
//創(chuàng)建不同的文件夾目錄
File file=new File(filePath);
//判斷文件夾是否存在
if (!file.exists())
{
//如果文件夾不存在,則創(chuàng)建新的的文件夾
file.mkdirs();
}
FileOutputStream fileOut = null;
HttpURLConnection conn = null;
InputStream inputStream = null;
try
{
// 建立鏈接
URL httpUrl=new URL(url);
conn=(HttpURLConnection) httpUrl.openConnection();
//以Post方式提交表單,默認(rèn)get方式
conn.setRequestMethod(method);
conn.setDoInput(true);
conn.setDoOutput(true);
// post方式不能使用緩存
conn.setUseCaches(false);
//連接指定的資源
conn.connect();
//獲取網(wǎng)絡(luò)輸入流
inputStream=conn.getInputStream();
BufferedInputStream bis = new BufferedInputStream(inputStream);
//判斷文件的保存路徑后面是否以/結(jié)尾
if (!filePath.endsWith("/")) {
filePath += "/";
}
//寫(xiě)入到文件(注意文件保存路徑的后面一定要加上文件的名稱(chēng))
fileOut = new FileOutputStream(filePath+"123.png");
BufferedOutputStream bos = new BufferedOutputStream(fileOut);
byte[] buf = new byte[4096];
int length = bis.read(buf);
//保存文件
while(length != -1)
{
bos.write(buf, 0, length);
length = bis.read(buf);
}
bos.close();
bis.close();
conn.disconnect();
} catch (Exception e)
{
e.printStackTrace();
System.out.println("拋出異常!!");
}
return file;
}
/**
* @param args
*/
public static void main(String[] args)
{
String photoUrl = "https://ss0.bdstatic.com/5aV1bjqh_Q23odCf/static/superman/img/logo/bd_logo1_31bdc765.png";
String fileName = photoUrl.substring(photoUrl.lastIndexOf("/"));
//System.out.println("fileName---->"+fileName);
String filePath = "d:";
File file = saveUrlAs(photoUrl, filePath + fileName,"GET");
System.out.println("Run ok!/n<BR>Get URL file " + file);
}
相關(guān)閱讀
0基礎(chǔ) 0學(xué)費(fèi) 15天面授
有基礎(chǔ) 直達(dá)就業(yè)
業(yè)余時(shí)間 高薪轉(zhuǎn)行
工作1~3年,加薪神器
工作3~5年,晉升架構(gòu)
提交申請(qǐng)后,顧問(wèn)老師會(huì)電話(huà)與您溝通安排學(xué)習(xí)
初級(jí) 202925
初級(jí) 203221
初級(jí) 202629
初級(jí) 203743