开发者

File download involving HTTP Basic Authentication

开发者 https://www.devze.com 2023-02-15 18:52 出处:网络
In my Java program i want to download a file fr开发者_开发百科om a server that uses Http Basic Authentication. Can i use the URL class of java.net package for this purpose ?.If not,which java class sh

In my Java program i want to download a file fr开发者_开发百科om a server that uses Http Basic Authentication. Can i use the URL class of java.net package for this purpose ?.If not,which java class should i use ?

Please Help Thank You


Highly recommend Apache HTTP Client


Yes you can:

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();


finally, I solved the problem using this function:

    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();    }


This code worked for me, for retrieving a report from Stripe in October of 2020. But it uses apache-commons-io 2.8.0 and 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
      }
0

精彩评论

暂无评论...
验证码 换一张
取 消