Basic Authentication with RestTemplate (3.1)

apache-httpclient-4.x, basic-authentication, java, resttemplate, spring-mvc

Solution

Instantiating using

HttpClient client = new HttpClient();

doesn't exist anymore and class `DefaultHttpClient` is deprecated from HttpComponents HttpClient from version 4.3. So other answer are either invalid or deprecated. Here is my version, I wrote this class for rest requests which require basic authentication:

import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.HttpClient;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.HttpClients;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;

public class RestClient extends RestTemplate {
    public RestClient(String username, String password) {
        CredentialsProvider credsProvider = new BasicCredentialsProvider();
        credsProvider.setCredentials(
                new AuthScope(null, -1),
                new UsernamePasswordCredentials(username, password));
        HttpClient httpClient = HttpClients.custom().setDefaultCredentialsProvider(credsProvider).build();
        setRequestFactory(new HttpComponentsClientHttpRequestFactory(httpClient));
    }
}

Then use it like, for example:

RestClient restClient = new RestClient("username", "password");

String result = restClient.postForObject(...

Problem

I am trying to reproduce the following curl command using Java: ``` curl -v -u user:pass http://myapp.com/api ``` This command returns some JSON data. My buggy Java implementation is as follows: ``` @Test public void callTest() { RestTemplate restTemplate = createRestTemplate("user", "pass"); URI uri = new URI("http://myapp.com/api"); String res = restTemplate.getForObject(uri, String.class); } private static RestTemplate createRestTemplate(String username, String password) { UsernamePasswordCredentials cred = new UsernamePasswordCredentials(username, password); BasicCredentialsProvider cp = new BasicCredentialsProvider(); cp.setCredentials(AuthScope.ANY, cred); DefaultHttpClient client = new DefaultHttpClient(); client.setCredentialsProvider(cp); ClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory(client); RestTemplate restTemplate = new RestTemplate(factory); // set the media types properly return restTemplate; } ``` Yet, when I execute the test, it returns a `org.springframework.web.client.HttpClientErrorException: 401 Unauthorized` exception. When logging in `DEBUG`, I see no information about the authentication... What am I doing wrong while setting the authentication credentials?

Original source

Related problems