Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 480
Azeem Akram Avatar asked Dec 28 '25 21:12

Azeem Akram


1 Answers

You could just use the Base64 encode/decode capability that is present in the JDK itself. The package javax.xml.bind includes a class DatatypeConverter that provides methods to print/parse to various forms including

static byte[] parseBase64Binary(String lexicalXSDBase64Binary)
static String printBase64Binary(byte[] val)

Just import javax.xml.bind.DatatypeConverter and use the provided methods.

like image 97
Jere Avatar answered Dec 31 '25 11:12

Jere