用到的工具类:
https://github.com/josdejong/httputil
要注意的问题:
1)引入javax.servlet.http.*文件出错,是因为没有add library,要加server runtime
2)spring mvc无法requestMapping根目录,是因为配置了welcome-file
步骤:
1. 继承了HttpUtil的工具类
public class HttpUtilXml extends HttpUtil { /** * post an xml file */ static public String postXml(String url, String body, Mapheaders) throws IOException { // set content type if (headers == null) { headers = new HashMap (); } headers.put("Content-Type", "application/xml"); return post(url, body, headers); }}
这样就可以接受xml的数据。
2. 要引入两个依赖
com.fasterxml.jackson.core jackson-core 2.8.1 com.fasterxml.jackson.core jackson-databind 2.8.1
3. 实体类中加入xml注解
package com.hengzecn.car.entity;import java.io.Serializable;import javax.xml.bind.annotation.XmlElement;import javax.xml.bind.annotation.XmlRootElement;@XmlRootElement(name= "User")public class User implements Serializable{ private static final long serialVersionUID = 1L; private Integer id; private String userName; private String password; public User(Integer id, String userName, String password) { this.id = id; this.userName = userName; this.password = password; } public User(String userName, String password) { this.userName = userName; this.password = password; } public User() { } public Integer getId() { return id; } public String getUserName() { return userName; } public String getPassword() { return password; } @XmlElement public void setId(Integer id) { this.id = id; } @XmlElement public void setUserName(String userName) { this.userName = userName; } @XmlElement public void setPassword(String password) { this.password = password; }}
4. 接收xml文件
@RequestMapping(value = "/xml", method = RequestMethod.POST) @ResponseBody public User getXml(@RequestBody User user) { System.out.println(user.getPassword()); return user; }
5. 测试函数
@RequestMapping("/send_xml") public void sendXml() throws IOException{ String body = ""; String res = HttpUtilXml.postXml("http://129.0.5.11:8080/car/xml", body, null); //System.out.println(res); 1 fan 111
6. 测试截图
7. 下面要做的事情
将接收过来的xml持久化,存进数据库。
此文参考了 http://www.jianshu.com/p/7097fea8ce3f