springboot post xml
TestController.java
package com.done.posttest.controller; import com.done.posttest.model.Student; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; import org.springframework.http.MediaType; import org.springframework.util.LinkedMultiValueMap; import org.springframework.util.MultiValueMap; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.client.RestTemplate; import java.util.HashMap; import java.util.Map; @Api(description = "test") @RestController public class TestController { @PostMapping("received") @ApiOperation(value = "received", httpMethod = "POST", consumes = MediaType.APPLICATION_XML_VALUE , produces = MediaType.APPLICATION_XML_VALUE) public Map<Object,Object> received(@RequestBody Student student){ Map<Object,Object> map = new HashMap<>(); System.out.println(student); map.put("code",200); map.put("message","接收成功"); return map; } @PostMapping("send") public Map<Object,Object> send(){ Map<Object,Object> map = new HashMap<>(); RestTemplate restTemplate = new RestTemplate(); String url = "http://localhost:8700/received"; HttpHeaders requestHeader = new HttpHeaders(); requestHeader.setContentType(MediaType.APPLICATION_XML); StringBuffer xmlString = new StringBuffer(); xmlString.append("<student>") .append("<id>2</id>") .append("<name>jim</name>") .append("</student>"); HttpEntity<String> requestEntity = new HttpEntity<>(xmlString.toString(), requestHeader); String forObject = restTemplate.postForObject(url, requestEntity, String.class); map.put("code",200); map.put("message","发送成功"); map.put("data",forObject); return map; } }
Student.java
package com.done.posttest.model; import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlProperty; import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlRootElement; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import javax.xml.bind.annotation.*; import java.io.Serializable; @JacksonXmlRootElement(localName ="student") public class Student implements Serializable { @JacksonXmlProperty private String id; @JacksonXmlProperty private String name; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } }