Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android httpclient - getting a file with preemptive authentication

I have problems getting the HTML code of a website by using this example code.

http://svn.apache.org/repos/asf/httpcomponents/httpclient/branches/4.0.x/httpclient/src/examples/org/apache/http/examples/client/ClientPreemptiveBasicAuthentication.java

I have to use the above one, as I need preemptive authentication for my application in Android.

I thought the solution might be the httpget object, but I still get only errors :( c.f. HttpGet httpget = new HttpGet("/index.html");

Does anybody have an idea how to get the content of the file, which is specified in the httpget object above using the example code of the link. It definitely called, but for now I can only get status code and so on ...

Thanks 4 help

like image 268
Nils Avatar asked Jun 02 '10 18:06

Nils


4 Answers

When I tackled this last year, I gave up on HttpClient's native pre-emptive HTTP authentication and just rolled the header myself.

like image 119
CommonsWare Avatar answered Nov 04 '22 10:11

CommonsWare


Alternative 1: Please read Http Basic Authentication with Android that proposes a solution based on the HttpClient 4 official docs. I've not tested it by myself, so I'd be happy to know if it really works.

Edit: I've just tried it and it works like a charm.

Alternative 2: You can also add the "Authorization" HTTP header as proposed by @CommonsWare:

post.addHeader("Authorization", "Basic " + Base64.encode(username+":"+password));

In this case you need a Base64 encoder to encode the string containing the username and the password. You can find a lot of implementations in the Internet.

like image 37
Guido Avatar answered Nov 04 '22 11:11

Guido


For me the example above didn't work on Android. I had to do the following:

post.addHeader("Authorization", "Basic " + Base64.encodeToString((username+":"+password).getBytes(),Base64.NO_WRAP));
like image 9
janex Avatar answered Nov 04 '22 11:11

janex


Thanks janex.

I had to do the same on Android.

post.addHeader("Authorization", "Basic " + Base64.encodeToString((username+":"+password).getBytes(),Base64.NO_WRAP));

cheers

like image 7
Uros Majeric Avatar answered Nov 04 '22 10:11

Uros Majeric