本文介绍了如何使用Apache的HttpClient与Web认证做HTTP POST?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我寻觅了很多关于这一点,并不能找到一个体面的解决办法。使用凭据提供一来是糟糕,因为它使反对什么要求,即它激发请求通话量的两倍,得到了401才把大火与网络身份验证凭据请求。

I have searched a LOT for this and could not find a decent solution. The one using credentials provider is bad as it make double the amount of calls opposed to what is required i.e. it fires the request , gets a 401 and only then fires the request with the web auth credentials.

任何人谁使用Android的HttpClient库做的HTTP POST请求成功背后的权威性网页的URL?

Anyone who has used android's httpclient library to do http post requests to a URL behind web auth successfully??

推荐答案

有关HttpClient的使用4.0.x的一个Htt的prequestInterceptor使preemptive认证 - 因为 AndroidHttpClient 类不公开,你可能将不得不使用 DefaultHttpClient addRequestInterceptor(..)方法$ C>类。

For HttpClient 4.0.x you use a HttpRequestInterceptor to enable preemptive authentication - since the AndroidHttpClient class doesn't expose the addRequestInterceptor(..) method you're probably going to have to use the DefaultHttpClient class.

这个例子将垃圾邮件 USER1 / USER1 感兴趣的任何服务器。调整 AuthScope 如果你关心安全性,甚至一位。

This example will spam user1/user1 to any server interested. Adjust the AuthScope if you care even one bit about security.


DefaultHttpClient client = new DefaultHttpClient();
client.getCredentialsProvider().setCredentials(AuthScope.ANY, new UsernamePasswordCredentials("user1", "user1"));
client.addRequestInterceptor(new HttpRequestInterceptor() {
    public void process(HttpRequest request, HttpContext context) throws HttpException, IOException {
        AuthState state = (AuthState) context.getAttribute(ClientContext.TARGET_AUTH_STATE);
        if (state.getAuthScheme() == null) {
            BasicScheme scheme = new BasicScheme();
            CredentialsProvider credentialsProvider = (CredentialsProvider) context.getAttribute(ClientContext.CREDS_PROVIDER);
            Credentials credentials = credentialsProvider.getCredentials(AuthScope.ANY);
            if (credentials == null) {
                throw new HttpException();
            }
            state.setAuthScope(AuthScope.ANY);
            state.setAuthScheme(scheme);
            state.setCredentials(credentials);
        }
    }
}, 0); // 0 = first, and you really want to be first.

这篇关于如何使用Apache的HttpClient与Web认证做HTTP POST?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-20 23:29