我是Restful W-S的新手,我试图提供基本的Web服务。我无法传递XML内容(成功将其更改为纯文本时,我可以通过)
package com.controller;
import javax.validation.constraints.NotBlank;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import com.pojo.Student;
@RestController
public class Controllers {
@RequestMapping(value="/hi",method=RequestMethod.POST,consumes=MediaType.TEXT_PLAIN_VALUE,produces=MediaType.APPLICATION_XML_VALUE)
public String hello(@RequestBody String std) {
System.out.println(std);
return "Response";
}
}
package com.pojo;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement(name="student")
@XmlAccessorType(XmlAccessType.FIELD)
public class Student {
@XmlElement(name="str")
private String str;
public String getStr() {
return str;
}
public void setStr(String str) {
this.str = str;
}
}
客户端-
package com.me.app;
import java.io.StringWriter;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.web.client.RestTemplate;
import com.pojo.Student;
@SpringBootApplication
@ComponentScan(basePackageClasses=com.controller.Controllers.class)
public class App {
public static void main(String args[])
{
SpringApplication.run(App.class, args);
getEmployees();
}
private static void getEmployees()
{
System.out.println("starting");
final String uri = "http://localhost:8005/hi";
Student std = new Student();
std.setStr("Something");
String s=jaxbObjectToXML(std);
System.out.println(s);
RestTemplate restTemplate = new RestTemplate();
String result = restTemplate.postForObject(uri, s, String.class);
System.out.println(result);
}
private static String jaxbObjectToXML(Student std) {
String xmlString = "";
try {
JAXBContext context = JAXBContext.newInstance(Student.class);
Marshaller m = context.createMarshaller();
m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE); // To format XML
StringWriter sw = new StringWriter();
m.marshal(std, sw);
xmlString = sw.toString();
} catch (JAXBException e) {
e.printStackTrace();
}
return xmlString;
}
}
任何人都可以帮助我传递XML格式的内容。在上述情况下,我能够将文本作为内容传递,并且可以正常工作。
谢谢!