文件下载器中基本访问认证存在问题

11

我在我的应用程序中下载二进制文件(ZIP 文件)时遇到了问题。我必须使用基本访问身份验证来授权访问文件,但服务器响应始终为HTTP / 1.0 400错误请求。

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();

密码中的空格是否可能导致此问题?

1个回答

30

我可能有点晚了,但是我刚遇到了一个类似的问题。 问题出在以下这行代码:

String encoding = Base64.encodeToString(authentication.getBytes(), 0);
如果你将该行修改为以下内容,它应该可以工作:
String encoding = Base64.encodeToString(authentication.getBytes(), Base64.NO_WRAP);

默认情况下,Android Base64工具将在编码字符串的末尾添加一个换行符。这会使HTTP头失效并导致“错误请求”。

Base64.NO_WRAP标志告诉该工具创建不带换行符的编码字符串,从而保持HTTP头的完整性。


2
很好的答案,我吃了亏才发现。我在文档中找不到关于换行的任何信息。你知道这个在哪里/为什么要这样做吗? - sgarman
为什么他们要这样做! - Xample

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接