[ Calling a Rest URL written in Spring ]
I have a service like
@RequestMapping("/data")
@ResponseBody
public String property(@ModelAttribute("userDto") UserDto userDto ) {
System.out.println(userDto.getUsername());
System.out.println(userDto.getPassword());
return "Hello";
}
How do I call this WebService from a client. I wrote
UserDto userDto = new UserDto();
userDto.setUsername("dsf");
userDto.setPassword("dsf");
URL url = new URL("http://localhost:8080/home/property");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setConnectTimeout(1000);
conn.setReadTimeout(1000);
OutputStream os = conn.getOutputStream();
JAXBContext jc = JAXBContext.newInstance(userDto.getClass());
try {
jc.createMarshaller().marshal(userDto, os);
}
catch(Exception ex){
ex.printStackTrace();
}
os.flush();
But its not working. I'm getting a null value at the services end.
Answer 1
You need to encode your object suitably (usually XML or JSON) to send it over the stream.
JAXBContext jc = JAXBContext.newInstance(obj.getClass());
try ( OutputStream xml = connection.getOutputStream()) {
jc.createMarshaller().marshal(obj, xml);
}
Make sure you do:
connection.setRequestMethod("POST");
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type", "application/xml");
Before writing anything to the stream.
Your web service method should look like this:
@RequestMapping(value = "URLHere", method = RequestMethod.POST)
public String postGroupBody(
@RequestBody ObjectType object,
otherParamsHere) {
Answer 2
You can use RestTemplate
from spring to call these services.
String url = "http://localhost:8080/home/property";
UserDto userDto = new UserDto();
userDto.setUsername("dsf");
userDto.setPassword("dsf");
RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<UserDto> entity = new HttpEntity<UserDto>(userDto,headers);
ResponseEntity<ReturnedObject> result = restTemplate.exchange(url, HttpMethod.POST, entity, ReturnedObject.class);
ReturnedObject obj = result.getBody();
// you will get object returned by service in result.getBody();
Since you have not mentioned your service request format, I am assuming it's JSON, And you are using Jackson mapper to convert object to JSON and vice versa.
Answer 3
I guess you need to use @RequestBody instead of @ModelAttribute for your UserDto parameter.