【发布时间】:2019-06-24 16:01:23
【问题描述】:
我正在尝试创建一个在 JSON 解析后从 URL 下载文件的应用程序,但它是在应用程序目录中下载文件,而不是在客户端的下载文件夹中。 有人可以帮助我了解如何做到这一点吗?
这是我的代码:
@RequestMapping(value = "/", method = RequestMethod.GET)
public String getSteamingFile() throws Exception { //get method
File f = new File("t1.csv");
if(!f.exists() && !f.isDirectory()){
try {
URLConnection openConnection = new URL("https://www.dati.gov.it/api/3/action/package_show?id=537c1138-4c5f-41bb-aec8-862954b67b28").openConnection();
openConnection.addRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:25.0) Gecko/20100101 Firefox/25.0");
InputStream in = openConnection.getInputStream();
String data = "";
String line = "";
try {
InputStreamReader inR = new InputStreamReader(in);
BufferedReader buf = new BufferedReader(inR);
while (( line = buf.readLine()) != null) {
data+=line;
System.out.println(line);
}
} finally {
in.close();
}
JSONObject obj = (JSONObject) JSONValue.parseWithException(data);
JSONObject objI = (JSONObject) (obj.get("result"));
JSONArray objA = (JSONArray) (objI.get("resources"));
for(Object o: objA){ //json parse to get the url
if (o instanceof JSONObject) {
JSONObject o1 = (JSONObject)o;
String format = (String)o1.get("format");
String urlA = (String)o1.get("url");
urlA = urlA.replaceAll("&","&");
URL urlD = new URL (urlA);
System.out.println(format + " | " + urlD);
if(format.equals("csv")) {
File fname = new File ("t1.csv");
download(urlD, fname);
}
}
}
System.out.println( "OK" );
} catch (IOException e) {
e.printStackTrace();
}
}
else System.out.println("File presente, impossibile scaricare");
return "index";}
public static void download(URL url, File fileName) {
try {
FileUtils.copyURLToFile(url, fileName);
} catch (IOException e) {
System.out.println("Errore di Input/Output" + e);
}
}
【问题讨论】:
标签: spring file spring-boot download