文件下载涉及HTTP基本身份验证

时间:2011-03-10 07:26:59

标签: java

在我的Java程序中,我想从使用Http Basic Authentication的服务器下载文件。我可以为此目的使用java.net包的URL类吗?。如果不是,我应该使用哪个java类?

请帮助 谢谢

4 个答案:

答案 0 :(得分:2)

强烈推荐Apache HTTP Client

答案 1 :(得分:1)

是的,你可以:

final URL url = new URL(...);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();


if (username != null && username.trim().length() > 0 && password != null && password.trim().length() > 0) {
    final String authString = username + ":" + password;
    conn.setRequestProperty("Authorization", "Basic " + Base64.encodeBase64(authString.getBytes()));
}

conn.setRequestMethod("GET");
conn.setAllowUserInteraction(false);
conn.setDoInput(false);
conn.setDoOutput(true);

final OutputStream outs = conn.getOutputStream();

...

outs.close();

答案 2 :(得分:1)

最后,我使用此功能解决了问题:

    public void download(String url, String outPath, String authBase64) throws IOException {

    URL server = new URL(url); 

    URLConnection connection = (URLConnection) server.openConnection();

    connection.setRequestProperty("Authorization", "Basic " + authBase64);
    connection.connect();
    InputStream is = connection.getInputStream();

    FileOutputStream fos = new FileOutputStream(new File(outPath));

    byte[] buffer = new byte[4096];
    int n = 0;
    while (-1 != (n = is.read(buffer))) {
        fos.write(buffer, 0, n);
    }

    is.close();
    fos.close();    }

答案 3 :(得分:0)

此代码对我有用,可用于从2020年10月从Stripe检索报告。但是它使用apache-commons-io 2.8.0和Java 11。

      private java.io.File downloadCsvReport(final java.net.URI https) throws IOException {
    
        java.io.File output = new java.io.File("report.csv");
    
        java.net.URL url = https.toURL();
        javax.net.ssl.HttpsURLConnection secure = (javax.net.ssl.HttpsURLConnection) url.openConnection();
        secure.setAuthenticator(new Authenticator() {
          protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(un, pw.toCharArray());
          }
        });
        secure.connect();
        try (InputStream inputStream = secure.getInputStream()) {
          org.apache.commons.io.FileUtils.copyInputStreamToFile(inputStream, output);
        } // auto closes inputStream
        return output; // no cleanup
      }