java从接口直接下载文件到本地
生活随笔
收集整理的這篇文章主要介紹了
java从接口直接下载文件到本地
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
最近有個(gè)需求,要求從接口獲取(下載)word文件到本地,然后,把word文件轉(zhuǎn)換成PDF格式。先說一下從接口獲取文件到本地。
接口是這個(gè)樣子的,瀏覽器請(qǐng)求接口直接就下載文件了:如圖
現(xiàn)在不要從瀏覽器下載,而是通過java代碼下載。因?yàn)槲乙M(jìn)行批量下載大概有2000個(gè)word文檔。
代碼如下:
import java.io.*; import java.net.HttpURLConnection; import java.net.URL;public class GetFrom {public static void main(String[] args) throws Exception {String photoUrl = "下載地址";String fileName = "申請(qǐng)書";String filePath = "d:/自助取表/";saveUrlAs(photoUrl, filePath,fileName,"GET");System.out.println("下載完成!");}/*** @功能 下載材料接口* @param filePath 文件將要保存的目錄* @param method 請(qǐng)求方法,包括POST和GET* @param url 請(qǐng)求的路徑* @return*/public static void saveUrlAs(String url,String filePath,String fileName,String method){FileOutputStream fileOut = null;HttpURLConnection conn = null;InputStream inputStream = null;//創(chuàng)建不同的文件夾目錄File file=new File(filePath);//判斷文件夾是否存在if (!file.exists()){//如果文件夾不存在,則創(chuàng)建新的的文件夾file.mkdirs();}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 += "/";}//寫入到文件(注意文件保存路徑的后面一定要加上文件的名稱)fileOut = new FileOutputStream(filePath+fileName+".doc");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("拋出異常!!");}} }總結(jié)
以上是生活随笔為你收集整理的java从接口直接下载文件到本地的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Python 使用numpy报错:run
- 下一篇: ValueError: With n_s