通过HTTP将XML对象发送到POST REST服务

时间:2017-03-14 00:47:36

标签: java xml rest http post

我有一个EJB应用程序需要通过HTTP Post将XML对象发送到RESTfull服务。 (全部在同一个基础设施公园内)

我已经看到了一些XML对象在发送到服务之前转换为String的示例。但是,我想传递所有XML对象本身。 (我想这是可能的)

例如,在Web应用程序架构中,我会使用RestTemplate执行此操作,如下所示:

RestTemplate restTemplate = new RestTemplate();
EmployeeVO result = restTemplate.postForObject( uri, newEmployee, EmployeeVO.class);

现在,我严格应该使用HttpURLConnection来做同样的事情。

有人可以通过展示一些例子来帮助我吗? 其余服务仅使用“application / XML”并返回String。

关注我的RESTfull签名和我的XML对象。

RESTFull服务

@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";
    }

}

@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;
    }
}

提前致谢。

1 个答案:

答案 0 :(得分:2)

谢谢大家的想法!

我可以通过以下代码解决我的问题。

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();
相关问题