文件下载器中的基本访问身份验证问题 [英] Problem with basic access authentication in file downloader
问题描述
我在从互联网下载应用程序中的二进制文件(zip 文件)时遇到问题.我必须使用基本访问身份验证来授权访问文件,但服务器响应始终是 HTTP/1.0 400 错误请求.
I'm having problems with downloading binary file (zip file) in my app from te internet. I have to use basic access authentication to authorize acces to file, but server response is always HTTP/1.0 400 Bad request.
String authentication = this._login+":"+this._pass;
String encoding = Base64.encodeToString(authentication.getBytes(), 0);
String fileName = "data.zip";
URL url = new URL("http://10.0.2.2/androidapp/data.zip");
HttpURLConnection ucon = (HttpURLConnection) url.openConnection();
ucon.setRequestMethod("GET");
ucon.setDoOutput(true);
ucon.setRequestProperty ("Authorization", "Basic " + encoding);
ucon.connect();
/*
* Define InputStreams to read from the URLConnection.
*/
InputStream is = ucon.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
/*
* Read bytes to the Buffer until there is nothing more to read(-1).
*/
ByteArrayBuffer bab = new ByteArrayBuffer(50);
int current = 0;
while ((current = bis.read()) != -1) {
bab.append((byte) current);
}
bis.close();
/* Convert the Bytes read to a String. */
FileOutputStream fos = this._context.openFileOutput(fileName, this._context.MODE_WORLD_READABLE);
fos.write(bab.toByteArray());
fos.close();
会不会是密码中的空格引起的?
Could it be caused by whitespaces in password?
推荐答案
我可能有点晚了,但我刚刚遇到了类似的问题.问题在于以下几行:
I might be a bit late but I just came across a similar problem. The problem lies in the following line:
String encoding = Base64.encodeToString(authentication.getBytes(), 0);
如果您将该行更改为如下所示,它应该可以工作:
If you change that line to look like this it should work:
String encoding = Base64.encodeToString(authentication.getBytes(), Base64.NO_WRAP);
默认情况下,Android Base64 实用程序会在编码字符串的末尾添加一个换行符.这会使 HTTP 标头无效并导致错误请求".
By default the Android Base64 util adds a newline character to the end of the encoded string. This invalidates the HTTP headers and causes the "Bad request".
Base64.NO_WRAP 标志告诉实用程序创建没有换行符的编码字符串,从而保持 HTTP 标头完整.
The Base64.NO_WRAP flag tells the util to create the encoded string without the newline character thus keeping the HTTP headers intact.
这篇关于文件下载器中的基本访问身份验证问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!