如何在我的代码中使用 Base64.java 文件?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10945147/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to to use Base64.java file in my code?
提问by Azeem Akram
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();
}
}
}
- It works fine but gives an error " Cannot find symbol error Base64Encoder"
- Downloaded the Base64.java file
- 它工作正常,但出现错误“找不到符号错误 Base64Encoder”
- 下载了 Base64.java 文件
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?
现在我不知道如何在我的项目中使用这个文件来消除错误。你能告诉我如何使用 Base64.java 文件来消除错误吗?
Thanks in anticipation.
感谢期待。
采纳答案by AzizSM
Need to import the Base64
into your code. The import are depends on your source file.
Apache Commons Codechas a solid implementation of Base64.
需要将 导入Base64
到您的代码中。导入取决于您的源文件。
Apache Commons Codec具有可靠的 Base64 实现。
example:
例子:
import org.apache.commons.codec.binary.Base64;
回答by Jere
You could just use the Base64 encode/decode capability that is present in the JDK itself. The package javax.xml.bindincludes a class DatatypeConverterthat provides methods to print/parse to various forms including
您可以只使用 JDK 本身中存在的 Base64 编码/解码功能。包javax.xml.bind包含一个类DatatypeConverter,该类提供打印/解析为各种形式的方法,包括
static byte[] parseBase64Binary(String lexicalXSDBase64Binary)
static String printBase64Binary(byte[] val)
Just import javax.xml.bind.DatatypeConverterand use the provided methods.
只需导入javax.xml.bind.DatatypeConverter并使用提供的方法。