在文件下载基本的接入认证问题 [英] Problem with basic access authentication in file downloader

查看:146
本文介绍了在文件下载基本的接入认证问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有问题,下载二进制文件(zip文件)在我的应用程序从TE网络。我必须使用基本的接入认证授权的存取权限的文件,但服务器的响应始终是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的UTIL增加了一个换行符的EN codeD字符串的结尾。这种无效的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标志告诉UTIL创建EN codeD字符串没有这样的换行符保持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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆