我有一个 EJB 应用程序,需要通过 HTTP Post 将 XML 对象发送到 RESTfull 服务。 (全部位于同一个基础设施园区)
我见过一些例子,其中 XML 对象在发送到服务之前被转换为字符串。但是,我想传递所有 XML 对象本身。 (我想这是可能的)
例如,在 Web 应用程序架构中,我将使用 RestTemplate 来做到这一点,如下所示:
RestTemplate restTemplate = new RestTemplate();
EmployeeVO result = restTemplate.postForObject( uri, newEmployee, EmployeeVO.class);
现在,我严格应该使用 HttpURLConnection 来执行相同的操作。
有人可以帮我举一些例子吗? 其余服务仅使用“application/XML”并返回一个字符串。
遵循我的 RESTfull 签名和 XML 对象。
REST全方位服务
@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;
}
}
提前致谢。
最佳答案
谢谢大家的想法!
我可以通过执行以下代码来解决我的问题。
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();
关于java - 通过 HTTP 将 XML 对象发送到 POST REST 服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42776004/