开发者

Android httpclient - getting a file with preemptive authentication

开发者 https://www.devze.com 2023-01-01 19:12 出处:网络
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/example

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 st开发者_如何学Goatus code and so on ...

Thanks 4 help


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


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.


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


Thanks janex.

I had to do the same on Android.

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

cheers

0

精彩评论

暂无评论...
验证码 换一张
取 消