Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Problem with basic access authentication in file downloader

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?

like image 836
Kamil Avatar asked Sep 09 '10 14:09

Kamil


1 Answers

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.

like image 180
Heinrich Filter Avatar answered Oct 01 '22 09:10

Heinrich Filter