Search code examples
javajakarta-eebase64http-authentication

How to to use Base64.java file in my code?


I am trying this

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class HttpBasicAuth {

public static void downloadFileWithAuth(String urlStr, String user, String pass, String outFilePath) {
    try {
        // URL url = new URL ("http://ip:port/download_url");
        URL url = new URL(urlStr);
        String authStr = user + ":" + pass;
        String authEncoded = Base64.encodeBytes(authStr.getBytes());

        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("GET");
        connection.setDoOutput(true);
        connection.setRequestProperty("Authorization", "Basic " + authEncoded);

        File file = new File(outFilePath);
        InputStream in = (InputStream) connection.getInputStream();
        OutputStream out = new BufferedOutputStream(new FileOutputStream(file));
        for (int b; (b = in.read()) != -1;) {
            out.write(b);
        }
        out.close();
        in.close();
    }
    catch (Exception e) {
        e.printStackTrace();
    }
}
}
  1. It works fine but gives an error " Cannot find symbol error Base64Encoder"
  2. Downloaded the Base64.java file

Now I don't know how to use this file with my project to remove the error. can you tell me please the how to use the Base64.java file to remove the error?

Thanks in anticipation.


Solution

  • Need to import the Base64 into your code. The import are depends on your source file. Apache Commons Codec has a solid implementation of Base64.

    example:

    import org.apache.commons.codec.binary.Base64;