Apache HttpClientBuilder - IllegalArgumentException

时间:2014-11-19 06:59:13

标签: java android httpclient apache-httpclient-4.x apache-httpcomponents

尝试使用HttpClientBuilder构建Apache HttpClient实例时得到IllegalArgumentException

private CloseableHttpClient delegate;

public DigestClient(String user, String pass) {
    Credentials credentials = new UsernamePasswordCredentials(user, pass);

    CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    credentialsProvider.setCredentials(AuthScope.ANY, credentials);

    delegate = HttpClientBuilder.create()
            .setDefaultCredentialsProvider(credentialsProvider)
            .build();
}

我得到的是:

 java.lang.IllegalArgumentException: Item may not be null
        at org.apache.http.util.Args.notNull(Args.java:48)
        at org.apache.http.config.RegistryBuilder.register(RegistryBuilder.java:58)
        at org.apache.http.impl.client.HttpClientBuilder.build(HttpClientBuilder.java:727)
        at com.example.app.data.net.DigestClient.<init>(DigestClient.java:51)

为什么会发生这种情况?

这是我与HttpClient版本的关系:

compile 'org.apache.httpcomponents:httpclient-android:4.3.5'

3 个答案:

答案 0 :(得分:8)

升级httpclient-android版本为我修复了它:

compile 'org.apache.httpcomponents:httpclient-android:4.3.5.1'

答案 1 :(得分:3)

我在这里找到了一个解决方案:

  

http://javacave.blogspot.com/2014/08/androidapache-httpclient.html

对于那些不懂中文的人:

我必须这样做:

SSLContext sslContext = SSLContexts.createSystemDefault();
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext);

然后

delegate = HttpClients.custom()
            .setDefaultCredentialsProvider(credentialsProvider)
            .setSSLSocketFactory(sslsf)
            .build();

至少它不会以这种方式崩溃。

答案 2 :(得分:0)

private CloseableHttpClient delegate;

public DigestClient(String user, String pass) {
    Credentials credentials = new UsernamePasswordCredentials(user, pass);

    CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    credentialsProvider.setCredentials(AuthScope.ANY, credentials);

    delegate = HttpClientBuilder.create()
            .setDefaultCredentialsProvider(credentialsProvider)
            .build();
}