Problem with basic access authentication in file d

2019-04-05 02:18发布

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?

1条回答
来,给爷笑一个
2楼-- · 2019-04-05 02:37

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

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".

The Base64.NO_WRAP flag tells the util to create the encoded string without the newline character thus keeping the HTTP headers intact.

查看更多
登录 后发表回答