【问题标题】:Send XML object through HTTP to a POST REST Service通过 HTTP 将 XML 对象发送到 POST REST 服务
【发布时间】:2017-03-14 00:47:35
【问题描述】:

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

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

例如,在 Web 应用程序架构中,我会使用 RestTemplate 来做到这一点,如下所示:

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

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

有人可以通过展示一些例子来帮助我吗? 其余服务仅使用“应用程序/XML”并返回一个字符串。

按照我的 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;
    }
}

提前致谢。

【问题讨论】:

  • 你最好先尝试一下你的想法,如果失败了再问问题
  • 用apache客户端怎么样?
  • @efekctive,我忘了提到,在我的 EJB 应用程序中,我没有 Spring 作为依赖项,而且我不能包含它,因为架构解决方案旨在避免混合技术并获得代码上的意大利面条。特别是在可维护性方面。
  • @Yohannes 我严格应该使用 HttpUrlConnection(悲伤的脸)
  • 我认为你需要澄清你的想法。要发送任何对象,请使用序列化(想到 jaxb),它将对象转换为 xml/json 并进入有效负载。如果您拥有的 xml 在文件/字符串中,则创建一个对象以将其再次转换为 xml 是没有意义的

标签: java xml rest http post


【解决方案1】:

谢谢大家的意见!

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

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

【讨论】:

    猜你喜欢
    • 2016-01-30
    • 1970-01-01
    • 1970-01-01
    • 2012-10-22
    • 2014-06-10
    • 2014-03-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多