【问题标题】:type=Not Acceptable, status=406 Error In Spring Rest For Producing XMLtype=Not Acceptable, status=406 Spring Rest 生成 XML 错误
【发布时间】:2016-10-23 16:07:53
【问题描述】:

我正在开发 Spring Rest 和我的 Spring Rest 应用程序,如果我尝试生成 json,一切正常。我可以在浏览器上看到它。没有错误。

但如果我想生成 XML,我会使用 producer = "application/xml" 或 products=MediaType.TEXT_XML_VALUE 和 我收到此错误:

Whitelabel Error Page

This application has no explicit mapping for /error, so you are seeing this as a fallback.

Sun Oct 23 18:30:51 EEST 2016
There was an unexpected error (type=Not Acceptable, status=406).
Could not find acceptable representation

我的休息代码是:

package getExample;

import java.util.ArrayList;
import java.util.List;

import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import pojo.Address;
import pojo.Person;

@RestController
public class GetExampleController {

    @RequestMapping(value = "getExample",method=RequestMethod.GET,produces=MediaType.TEXT_XML_VALUE)
    public List<Person> getExample1(@RequestParam(value = "personId", defaultValue = "0") String id) {
        List<Person> personList = new ArrayList<>();
        Person person1 = new Person("1", "ilkay", "günel",
                new Address("Cennet Mah.", "K.Çekmece", "İstanbul", "TÜRKİYE"));
        personList.add(person1);

        Person person2 = new Person("2", "alican", "akkuş",
                new Address("Cennet Mah.", "K.Çekmece", "İstanbul", "TÜRKİYE"));
        personList.add(person2);

        Person person3 = new Person("3", "mustafa", "demir",
                new Address("Cennet Mah.", "K.Çekmece", "İstanbul", "TÜRKİYE"));
        personList.add(person3);

        if (id.equals("0")) {
            return personList;
        }
        else {
            return personList.subList(Integer.parseInt(id)-1, Integer.parseInt(id));
        }
    }
}

什么是错误?为什么我可以获得 XML 输出?我该如何解决这个问题?

【问题讨论】:

    标签: rest spring-boot


    【解决方案1】:

    需要添加jackson-dataformat-xml的依赖:

    <dependency>
        <groupId>com.fasterxml.jackson.dataformat</groupId>
        <artifactId>jackson-dataformat-xml</artifactId>
    </dependency>
    

    否则,您可以使用 JAXB 注释来注释您的 bean。

    Spring documentation:

    如果您有 Jackson XML 扩展 (jackson-dataformat-xml) 类路径,它将用于呈现 XML 响应,并且非常相同 我们用于 JSON 的示例可以工作。

    ...

    如果 Jackson 的 XML 扩展不可用,JAXB(默认提供 在 JDK 中)将被使用,附加要求是 [你的班级]注释为@XmlRootElement...

    ...

    要让服务器呈现 XML 而不是 JSON,您可能必须发送 一个 Accept: text/xml 标头(或使用浏览器)。

    【讨论】:

    • 谢谢 - 这正是我所缺少的。认为 spring boot starter 包含开箱即用的 xml 支持,但它没有。
    猜你喜欢
    • 2011-08-30
    • 2017-05-25
    • 2016-02-21
    • 2014-11-12
    • 2013-08-10
    • 2012-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多