Pergunta

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.

Foi útil?

Solução

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;

Outras dicas

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.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top