yongsup
yongsup

Reputation: 194

How to use Spring RestTemplate instead of Apache Httpclient?

I want to use Spring RestTemplate instead of Apache HttpClient for working with a remote API

With HttpClient

// 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);

With RestTemplate

Map<String, String> paramMap = new HashMap<String,String>();
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<String> request = new HttpEntity<String>(mapAsJson,requestHeaders);

try {
  ResponseEntity<String> response = restTemplate.exchange(AuthServer, HttpMethod.POST, request, String.class);

  return response.getHeaders();
} catch (HttpClientErrorException e) {
  return null;
}

}

The code with HttpClient works but that with RestTemplate does not. I don't know how to use StringEntity in RestTemplate.

Spring version is 3.0.0, and JVM is 1.6.

Upvotes: 0

Views: 4344

Answers (1)

manish
manish

Reputation: 20135

RestTemplate is better suited to working with objects. As an example:

AuthenticationRequest.java

class AuthenticationRequest {
  private String username;
  private String serial;
  private String key;
  private String otp;
}

AuthenticationResponse.java

class AuthenticationResponse {
  private boolean success;
}

AuthenticationCall.java

class AuthenticationCall {
  public AuthenticationResponse execute(AuthenticationRequest payload) {
    HttpEntity<AuthenticationRequest> request = new HttpEntity<AuthenticationRequest>(payload, new HttpHeaders());

    return restTemplate.exchange("http://www.domain.com/api/endpoint"
                                 , HttpMethod.POST
                                 , request
                                 , AuthenticationResponse.class).getBody();
  }
}

These classes can be used as follows:

if(new AuthenticationCall().execute(authenticationRequest).isSuccess()) {
  // Authentication succeeded.
}
else {
  // Authentication failed.
}

All of this requires there to be a JSON library such as Jackson or GSON on the classpath.

Upvotes: 1

Related Questions