How to download a file from a resource with the original name and extension? I know that File has a getName() method, how to substitute the file name instead of " w4.pdf "? Maybe I chose the wrong solution?

  String url = "https://onedrive.live.com/download?resid=72571393D4771099!7571&authkey=!AKRZuNSbUxV2I1I&ithint=file%2cpdf"; HttpURLConnection httpURLConnection; try { httpURLConnection = (HttpURLConnection) new URL(url).openConnection(); System.out.println("code response : " + httpURLConnection.getResponseCode()); BufferedInputStream bis = new BufferedInputStream(httpURLConnection.getInputStream()); BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(new File("E:\\w4.pdf"))); int c; while ((c = bis.read()) != -1) { bos.write(c); } bos.close(); bis.close(); } catch (IOException e) { e.printStackTrace(); } 
  • And how is the file itself called? - alexandr gaiduchok
  • unknown, the file name can be of any kind - GoodWin
  • one
    See what the "Content-Disposition" response header ( httpURLConnection.getHeaderField("Content-Disposition") ) contains. There should be something like "attachment; filename=filename.ext" , from where you can take out the contents of the regular / substring. For names containing only ascii characters, everything is simple, for others it is somewhat more difficult - zRrr
  • "Content-Disposition" returns null if the link is direct to the file, for example https://site.com/img/image.jpg . How can this problem be solved? - GoodWin
  • if the link is in the main question, then everything is OK, the "Content-Disposition" contains the Content-Disposition : attachment; filename*=UTF-8''%d0%94%d0%be%d0%b4%d0%b0%d1%82%d0%be%d0%ba2.doc Content-Disposition : attachment; filename*=UTF-8''%d0%94%d0%be%d0%b4%d0%b0%d1%82%d0%be%d0%ba2.doc , but there is already a question to pick out the name of the file and translate into the Latin - GoodWin

1 answer 1

At random, but tried to remake the line like this: BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(new File("E:\\"+bis.toString()))); Already I checked it myself, it does not plow. In general, all this is simpler with FileUtils