title: Basic Authentication with RestTemplate (3.1)
body: <p>I am trying to reproduce the following curl command using Java:</p>
  
  <pre><code>curl -v -u user:pass http://myapp.com/api
  </code></pre>
  
  <p>This command returns some JSON data.</p>
  
  <p>My buggy Java implementation is as follows:</p>
  
  <pre><code>@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;
  }
  </code></pre>
  
  <p>Yet, when I execute the test, it returns a <code>org.springframework.web.client.HttpClientErrorException: 401 Unauthorized</code> exception.</p>
  
  <p>When logging in <code>DEBUG</code>, I see no information about the authentication...</p>
  
  <p>What am I doing wrong while setting the authentication credentials?</p>