Sample user class:
public class User
{
private String user;
private String name;
public String getUser()
{
return user;
}
public void setUser(String user)
{
this.user = user;
}
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
}
Time for the Client Code
public class Main
{
public static void main(String[] args) throws IOException
{
/**
*
* This is setting the REST server configuration in the applicationContext
*
*/
ApplicationContext context = new AnnotationConfigApplicationContext(RESTConfiguration.class);
/**
*
* We now get a RESTServer bean from the ApplicationContext which has all the data we need to
* log into the REST service with.
*
*/
RESTServer mRESTServer = context.getBean(RESTServer.class);
/**
*
* Setting up data to be sent to REST service
*
*/
Map<String, String> vars = new HashMap<String, String>();
vars.put("id", "JS01");
try
{
/*
Code to post and return a user object
*/
RestTemplate rt = new RestTemplate();
rt.getMessageConverters().add(new MappingJacksonHttpMessageConverter());
rt.getMessageConverters().add(new StringHttpMessageConverter());
String uri = new String("http://" + mRESTServer.getHost() + ":8080/springmvc-resttemplate-test/api/{id}");
User u = new User();
u.setName("M Shah");
u.setUser("MS01");
User returns = rt.postForObject(uri, u, User.class, vars);
}
catch (HttpClientErrorException e)
{
ObjectMapper mapper = new ObjectMapper();
ErrorHolder eh = mapper.readValue(e.getResponseBodyAsString(), ErrorHolder.class);
}
catch(Exception e)
{
}
}
}
Comment below if you have any questions/concern.