title: Android RestTemplate exchange() throws HttpClientErrorException: 401 Unauthorized
body: <p>I am trying to connect to a RESTful web service from an Android client.</p>
  
  <p>However, I always get a <code>HttpClientErrorException: 401 Unauthorized even if provide the correct authorization token in the request header.</code></p>
  
  <p>The url provided is correct.</p>
  
  <p>I have also tried with this request factory:</p>
  
  <pre><code>template.setRequestFactory(new SimpleClientHttpRequestFactory());
  </code></pre>
  
  <p>If i use Postman for Chorme with the same headers and url I get a response.</p>
  
  <p>This is my code:</p>
  
  <pre><code>public class PutSomeObjectTask extends AsyncTask&lt;SomeObject, Void, SomeObject&gt;{
  
  @Override
  protected SomeObject doInBackground(SomeObject... params) {
      SomeObject object = params[0];
      String url = ...;
  
      RestTemplate template = new RestTemplate();
      template.setRequestFactory(new HttpComponentsClientHttpRequestFactory());
      template.getMessageConverters().add(new MappingJackson2HttpMessageConverter());
      template.getMessageConverters().add(new FormHttpMessageConverter());
  
      HttpHeaders headers = new HttpHeaders();
      headers.add("Content-Type", "application/json");
      headers.set("Authorization", AuthUtil.getCurrentUserAuthorization());
  
      HttpEntity&lt;SomeObject&gt; requestEntity = new HttpEntity&lt;SomeObject&gt;(object, headers);
      ResponseEntity&lt;SomeObject&gt; responseEntity = template.exchange(url, HttpMethod.PUT, requestEntity, SomeObject.class);
  
      return responseEntity.getBody();
  }}
  </code></pre>