Reputation: 55
I have an EJB application which needs to send a XML object to a RESTfull service through HTTP Post. (All in the same infrastructure park)
I have seen some examples which the XML object is converted to String before send it to the service. However, I want to pass all the XML object itself. (I suppose it's possible)
For instance, in a web application architecture, I would do that by using RestTemplate, as follow:
RestTemplate restTemplate = new RestTemplate();
EmployeeVO result = restTemplate.postForObject( uri, newEmployee, EmployeeVO.class);
Now, I strictly should do the same using HttpURLConnection instead.
Someone can help me by showing some example? The rest service only consumes "application/XML" and returns a String.
Follow my RESTfull signature and my XML object.
RESTFull Service
@RestController
@RequestMapping(value = "/analytic/")
public class AnalyticController {
@RequestMapping(value = "/requestProcessor", method = RequestMethod.POST, consumes = MediaType.APPLICATION_XML_VALUE)
public String analyticRequest(@RequestBody ServiceRequest serviceRequest){
//Some code here...
return "0";
}
}
Domain
@XmlRootElement(name = "ServiceRequest")
public class ServiceRequest implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
@XmlAttribute(name = "Method")
private String method;
@XmlElement(name = "Credential")
private Credential credential;
public String getMethod() {
return method;
}
public void setMethod(String method) {
this.method = method;
}
public Credential getCredential() {
return credential;
}
public void setCredential(Credential credential) {
this.credential = credential;
}
}
Thanks in advance.
Upvotes: 2
Views: 4380
Reputation: 55
Thank you all for your thoughts!
I could solve my issue by doing the below code.
URL url = new URL("http://server:port/service_path");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setInstanceFollowRedirects(false);
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/xml");
OutputStream os = connection.getOutputStream();
JAXBContext jaxbContext = JAXBContext.newInstance(MyClass.class);
jaxbContext.createMarshaller().marshal(MyClass, os);
os.flush();
Upvotes: 2