title: How to use Spring RestTemplate instead of Apache Httpclient?
body: <p>I want to use Spring <code>RestTemplate</code> instead of Apache <code>HttpClient</code> for working with a remote API</p>
  
  <blockquote>
    <p>With <strong>HttpClient</strong></p>
  </blockquote>
  
  <pre><code>// build request JSON
  JSONObject json = new JSONObject();
  json.put("username", username);
  json.put("serial", serial);
  json.put("keyId", keyId);
  json.put("otp", otp);
  
  String json_req = json.toString();           
  
  // make HTTP request and get response
  HttpPost request = new HttpPost(AuthServer);
  request.setHeader("Content-Type", "application/json");
  request.setEntity(new StringEntity(json_req));
  
  response = client.execute(request);
  </code></pre>
  
  <blockquote>
    <p>With <strong>RestTemplate</strong></p>
  </blockquote>
  
  <pre><code>Map&lt;String, String&gt; paramMap = new HashMap&lt;String,String&gt;();
  paramMap.put("username", userName);
  paramMap.put("serial", serial);
  paramMap.put("keyId", keyId);
  paramMap.put("otp", otp);
  
  String mapAsJson = new ObjectMapper().writeValueAsString(paramMap);
  
  HttpHeaders requestHeaders = new HttpHeaders();
  requestHeaders.setContentType(MediaType.APPLICATION_JSON);
  HttpEntity&lt;String&gt; request = new HttpEntity&lt;String&gt;(mapAsJson,requestHeaders);
  
  try {
    ResponseEntity&lt;String&gt; response = restTemplate.exchange(AuthServer, HttpMethod.POST, request, String.class);
  
    return response.getHeaders();
  } catch (HttpClientErrorException e) {
    return null;
  }
  </code></pre>
  
  <p>}</p>
  
  <p>The code with <code>HttpClient</code> works but that with <code>RestTemplate</code> does not. I don't know how to use <code>StringEntity</code> in <code>RestTemplate</code>.</p>
  
  <p>Spring version is 3.0.0, and JVM is 1.6.</p>