简体   繁体   English

Java URL文件下载

[英]java URL file download

I am trying to create a java console app which will download a file from a URL. 我正在尝试创建一个Java控制台应用程序,它将从URL下载文件。 The file is created at Runtime and I don't know the file name. 该文件是在运行时创建的,我不知道文件名。 When I copy and paste the URL in the browser the save file pop up comes up to save the file. 当我在浏览器中复制并粘贴URL时,会弹出弹出的保存文件以保存文件。 Now I want to create Java code which logs on to the server (validates user I have that done) go to that URL and download the file. 现在,我想创建登录到服务器的Java代码(验证已完成的用户)转到该URL并下载文件。

Sergii's answer is a good start; Sergii的答案是一个好的开始。 however, if the website you want to use requires more that a simple download, consider using Apache's HttpClient . 但是,如果您要使用的网站需要比简单下载更多的内容,请考虑使用Apache的HttpClient

It supports cookies, authentication, URIs as well as URLs, and file upload. 它支持cookie,身份验证,URI,URL和文件上传。

Simple exapmple from docs, just to put your url insted of http://www.oracle.com/ , and change System.out.println(inputLine); 来自文档的简单示例,只是将您的网址插入http://www.oracle.com/ ,并更改System.out.println(inputLine); to write file on disk. 在磁盘上写入文件。

import java.net.*;
import java.io.*;

public class URLReader {
    public static void main(String[] args) throws Exception {

        URL oracle = new URL("http://www.oracle.com/");
        BufferedReader in = new BufferedReader(
        new InputStreamReader(oracle.openStream()));

        String inputLine;
        while ((inputLine = in.readLine()) != null)
            System.out.println(inputLine);
        in.close();
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM