3

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.

Azeem Akram
  • 223
  • 6
  • 9
  • 21
  • Which library did you download Base64.java from? You should probably include the entire library rather than copying and compiling just Base64.java. – dejuknow Jun 08 '12 at 08:13
  • From here http://sourceforge.net/projects/iharder/files/base64/2.3/ I have downloaded it. currently I am not getting anything, I am new to java, so can you help me that what to do now? – Azeem Akram Jun 08 '12 at 08:15
  • Please take a look here: [link](http://stackoverflow.com/questions/469695/decode-base64-data-in-java). It'll point you to some commonly used Base64 libraries and how to use them. – dejuknow Jun 08 '12 at 08:17

2 Answers2

2

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.

Jere
  • 581
  • 2
  • 3
1

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;
AzizSM
  • 6,199
  • 4
  • 42
  • 53