Kam*_*mil 11 java android apache2
我在从我的应用程序从互联网下载二进制文件(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();
Run Code Online (Sandbox Code Playgroud)
它可能是由密码中的空格引起的吗?
Hei*_*ter 30
我可能有点晚了,但我遇到了类似的问题.问题在于以下几行:
String encoding = Base64.encodeToString(authentication.getBytes(), 0);
Run Code Online (Sandbox Code Playgroud)
如果您将该行更改为这样,它应该工作:
String encoding = Base64.encodeToString(authentication.getBytes(), Base64.NO_WRAP);
Run Code Online (Sandbox Code Playgroud)
默认情况下,Android Base64 util会在编码字符串的末尾添加换行符.这会使HTTP标头无效并导致"错误请求".
Base64.NO_WRAP标志告诉util创建没有换行符的编码字符串,从而保持HTTP头不变.
| 归档时间: |
|
| 查看次数: |
1943 次 |
| 最近记录: |