简体   繁体   English

如何从Spring Rest服务返回XML响应?

[英]How do I return an XML response from a spring rest service?

I'm trying to return an xml response in my simple spring rest service. 我正在尝试在我的简单spring rest服务中返回xml响应。 I used spring initializr to start and created some employee class and a client to send requests. 我使用spring initializr来启动并创建了一些雇员类和一个客户端来发送请求。 The default seems to be JSON input and output but when I try to change it to XML, it still responds in JSON. 默认值似乎是JSON输入和输出,但是当我尝试将其更改为XML时,它仍然以JSON响应。

I've tried adding the XML annotations in the employee class, as well as @ResponseBody next to the @GetMapping methods. 我试过在employee类中以及@GetMapping方法旁边的@ResponseBody中添加XML批注。 I've also seen some other ways where you need to add some kind of spring configuration, but spring initializr didn't include any config file, just a pom.xml. 我还看到了一些其他方法,需要在其中添加某种类型的spring配置,但是spring initializr不包含任何配置文件,仅包含pom.xml。

EmployeeController.java EmployeeController.java


@RestController
public class EmployeeController {

    @Autowired
    private EmployeeService employeeService;

    @GetMapping("/employees")
    public @ResponseBody HashMap<String, Employee> retrieveEmployees() {
        return employeeService.retrieveAllEmployees();
    }

    @GetMapping("/employees/{employeeId}")
    public @ResponseBody Employee retrievebyId(@PathVariable String employeeId) {
        return employeeService.retrieveEmployee(employeeId);
    }

    @PostMapping(path="/employees")
    public ResponseEntity<Void> registeremployee(@RequestBody Employee newemployee) {

        Employee employee = employeeService.addEmployee(newemployee.getId(),newemployee.getName(), newemployee.getDescription());

        if (employee == null)
            return ResponseEntity.noContent().build();

        URI location = ServletUriComponentsBuilder.fromCurrentRequest().path(
                "/{id}").buildAndExpand(employee.getId()).toUri();

        return ResponseEntity.created(location).build();
    }

}

Employee.java Employee.java

@XmlRootElement (name = "employee")
@XmlAccessorType(XmlAccessType.NONE)
public class Employee implements Serializable {

    @XmlAttribute
    private String id;

    @XmlElement
    private String name;

    @XmlElement
    private String description;
    //private List<Team> teams;


    public Employee() {
        super();
    }

    public Employee(String id, String name, String description) {
        this.id = id;
        this.name = name;
        this.description = description;
        //this.teams = teams;

    }


    @XmlAttribute
    public String getId() {
        return id;
    }
    @XmlAttribute
    public void setId(String id) {
        this.id = id;
    }
    @XmlElement
    public String getName() {
        return name;
    }
    @XmlElement
    public void setName(String name) {
        this.name = name;
    }
    @XmlElement
    public String getDescription() {
        return description;
    }

//  public List<Team> getTeam() {
//      return teams;
//  }
    @XmlElement
    public void setDescription(String description) {
        this.description = description;
    }





    @Override
    public String toString() {
        return String.format(
                "employee [id=%s, name=%s, description=%s]", id,
                name, description);
    }
}

EmployeeService.java EmployeeService.java

@Component
public class EmployeeService {


    static HashMap<String, Employee> employees = new HashMap<>();


    static {
        //Initialize Data

        Team team1 = new Team("t1", "Java team", "Java Dev Team");

        Employee Joe = new Employee("employee1", "Joe Smith","Human Resources");

        Employee Bob = new Employee("employee2", "Bob Jones",
                "Developer");

        employees.put("employee1", Joe);
        employees.put("employee2", Bob);
    }

    public HashMap<String, Employee> retrieveAllEmployees() {
        return employees;
    }

    public Employee retrieveEmployee(String employeeId) {
        return employees.get(employeeId);
    }
    //private SecureRandom random = new SecureRandom();

    public Employee addEmployee(String id, String name, String description) {

        //String randomId = new BigInteger(130, random).toString(32);
        Employee employee = new Employee(id, name, description);

        employees.put(id, employee);

        return employee;
    }
}

RestClient.java RestClient.java

public class RestClient {

     public static void getJsonEmployee(String id) throws JSONException, IOException {

         String uri = "http://localhost:8080/employees/" + id;

         RestTemplate restTemplate = new RestTemplate();
//       HttpHeaders httpHeaders = restTemplate.headForHeaders(uri);
//
//          
//       httpHeaders.setContentType(MediaType.APPLICATION_XML);

         String result = restTemplate.getForObject(uri, String.class);
         System.out.println(result);

         }




public static void postJsonEmployee(String id, String name, String description) {

    final String uri = "http://localhost:8080/employees/";


    Employee newemp = new Employee(id, name, description);


    RestTemplate restTemplate = new RestTemplate();


    HttpHeaders httpHeaders = restTemplate.headForHeaders(uri);


    httpHeaders.setContentType(MediaType.APPLICATION_XML);


    Employee result = restTemplate.postForObject( uri, newemp, Employee.class);


    httpHeaders.setContentType(MediaType.APPLICATION_XML);


     }

    public static void main(String[] args) throws IOException, JSONException {

     System.out.println("GET or POST?");
     BufferedReader getpost = new BufferedReader(new InputStreamReader(System.in));
     String selection = getpost.readLine();

     switch(selection) {

     case "GET":

     System.out.println("Type in the employee's ID");
     BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
     String employeeid = reader.readLine();
     getJsonEmployee(employeeid);
     break;

     case "POST":

         System.out.println("Type in the employee's ID");
         Scanner scan = new Scanner(System.in);
         String newid = scan.nextLine();
         System.out.println("Type in the employee's name");
         String newname = scan.nextLine();
         System.out.println("Type in the employee's description");
         String newdesc = scan.nextLine();
         postJsonEmployee(newid, newname, newdesc);
         break;
     }

}

Result message: 结果消息:

13:18:14.726 [main] DEBUG org.springframework.web.client.RestTemplate - HTTP GET http://localhost:8080/employees/ 13:18:14.726 [main]调试org.springframework.web.client.RestTemplate-HTTP GET http:// localhost:8080 / employees /

13:18:14.737 [main] DEBUG org.springframework.web.client.RestTemplate - Accept=[text/plain, application/json, application/*+json, / ] 13:18:14.737 [main]调试org.springframework.web.client.RestTemplate-Accept = [text / plain,application / json,application / * + json, / ]

13:18:14.760 [main] DEBUG org.springframework.web.client.RestTemplate - Response 200 OK 13:18:14.761 [main] DEBUG org.springframework.web.client.RestTemplate - Reading to [java.lang.String] as "application/json;charset=UTF-8" 13:18:14.760 [main]调试org.springframework.web.client.RestTemplate-响应200 OK 13:18:14.761 [main]调试org.springframework.web.client.RestTemplate-读取[java.lang.String]为“ application / json; charset = UTF-8”

{"employee1":{"id":"employee1","name":"Joe Smith","description":"Human Resources"},"employee2":{"id":"employee2","name":"Bob Jones","description":"Developer"}} {“ employee1”:{“ id”:“ employee1”,“ name”:“ Joe Smith”,“ description”:“人力资源”},“ employee2”:{“ id”:“ employee2”,“ name”: “鲍勃·琼斯(Bob Jones)”,“描述”:“开发人员”}}

You need to update your mapping to: 您需要将映射更新为:

@GetMapping("/employees", produces = MediaType.APPLICATION_XML_VALUE)

Also, make sure you have public getters and setters in your EmployeeService.java class. 此外,请确保您有公共getterssettersEmployeeService.java类。

You have to use instead of this line 您必须使用而不是此行

httpHeaders.setContentType(MediaType.APPLICATION_XML);

with

headers.setAccept(Collections.singletonList(MediaType.APPLICATION_XML));

in RestTemplate header. 在RestTemplate标头中。

You can also do it in this manner. 您也可以通过这种方式进行操作。

headers.set("Accept", MediaType.APPLICATION_XML);

Also you have to support both XML and JSON in case of Rest end point as per the following. 另外,如果要使用Rest端点,则必须同时支持XML和JSON,如下所示。

@GetMapping(path = "/{your path}", produces = {MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_XML_VALUE})

I think you have problem with configuraion you can reffer this link it might useful. 我认为您在配置方面遇到问题,可以推荐此链接,它可能很有用。 https://howtodoinjava.com/spring-restful/spring-rest-hello-world-xml-example/ https://howtodoinjava.com/spring-restful/spring-rest-hello-world-xml-example/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM