[英]"Could not find acceptable representation" using spring-boot-starter-web
I am trying to use spring-boot-starter-web
to create a rest service serving up JSON representations of Java objects.我正在尝试使用
spring-boot-starter-web
创建一个 rest 服务,服务于 Java 对象的 JSON 表示。 From what I understand this boot-starter-web jar is supposed to handle the conversion to JSON through Jackson automatically but I am instead getting this error.据我了解,这个 boot-starter-web jar 应该自动处理到 JSON 到 Jackson 的转换,但我却收到了这个错误。
{
"timestamp": 1423693929568,
"status": 406,
"error": "Not Acceptable",
"exception": "org.springframework.web.HttpMediaTypeNotAcceptableException",
"message": "Could not find acceptable representation"
}
My Controller is this...我的Controller是这个...
@RestController
@RequestMapping(value = "/media")
public class MediaController {
@RequestMapping(value = "/test", method = RequestMethod.POST)
public @ResponseBody UploadResult test(@RequestParam(value="data") final String data) {
String value = "hello, test with data [" + data + "]";
return new UploadResult(value);
}
@RequestMapping(value = "/test2", method = RequestMethod.POST)
public int test2() {
return 42;
}
@RequestMapping(value = "/test3", method = RequestMethod.POST)
public String test3(@RequestParam(value="data") final String data) {
String value = "hello, test with data [" + data + "]";
UploadResult upload = new UploadResult(value);
return upload.value;
}
public static class UploadResult {
private String value;
public UploadResult(final String value)
{
this.value = value;
}
}
}
My pom.xml
has...我的
pom.xml
有...
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>1.2.1.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<version>1.2.1.RELEASE</version>
<scope>provided</scope>
</dependency>
mvn dependency:tree
shows that spring-boot-starter-web does indeed depend on the jackson2.4 databind and thus should be on the classpath... mvn dependency:tree
显示 spring-boot-starter-web 确实依赖于 jackson2.4 数据绑定,因此应该在类路径上......
[INFO] +- org.springframework.boot:spring-boot-starter-web:jar:1.2.1.RELEASE:compile
[INFO] | +- org.springframework.boot:spring-boot-starter:jar:1.2.1.RELEASE:compile
[INFO] | | +- org.springframework.boot:spring-boot:jar:1.2.1.RELEASE:compile
[INFO] | | +- org.springframework.boot:spring-boot-autoconfigure:jar:1.2.1.RELEASE:compile
[INFO] | | +- org.springframework.boot:spring-boot-starter-logging:jar:1.2.1.RELEASE:compile
[INFO] | | | +- org.slf4j:jul-to-slf4j:jar:1.7.8:compile
[INFO] | | | \- org.slf4j:log4j-over-slf4j:jar:1.7.8:compile
[INFO] | | \- org.yaml:snakeyaml:jar:1.14:runtime
[INFO] | +- com.fasterxml.jackson.core:jackson-databind:jar:2.4.4:compile
[INFO] | | +- com.fasterxml.jackson.core:jackson-annotations:jar:2.4.0:compile
[INFO] | | \- com.fasterxml.jackson.core:jackson-core:jar:2.4.4:compile
[INFO] | +- org.hibernate:hibernate-validator:jar:5.1.3.Final:compile
[INFO] | | +- javax.validation:validation-api:jar:1.1.0.Final:compile
[INFO] | | +- org.jboss.logging:jboss-logging:jar:3.1.3.GA:compile
[INFO] | | \- com.fasterxml:classmate:jar:1.0.0:compile
[INFO] | +- org.springframework:spring-web:jar:4.1.4.RELEASE:compile
[INFO] | | +- org.springframework:spring-aop:jar:4.1.4.RELEASE:compile
[INFO] | | | \- aopalliance:aopalliance:jar:1.0:compile
[INFO] | | +- org.springframework:spring-beans:jar:4.1.4.RELEASE:compile
[INFO] | | \- org.springframework:spring-context:jar:4.1.4.RELEASE:compile
[INFO] | \- org.springframework:spring-webmvc:jar:4.1.4.RELEASE:compile
[INFO] | \- org.springframework:spring-expression:jar:4.1.4.RELEASE:compile
... yet calling the test
service gives the error mentioned above. ...但调用
test
服务会出现上述错误。 test2
and test3
work fine proving that it must just be the attempted conversion to JSON that is failing? test2
和test3
工作正常,证明一定是尝试转换为 JSON 失败了? Am I missing some configuration problem or annotations?我是否遗漏了一些配置问题或注释? From all the examples I can find, annotating the class for basic Jackson JSON conversion is no longer necessary.
从我能找到的所有示例中,不再需要将 class 注释为基本的 Jackson JSON 转换。
Any help greatly appreciated.非常感谢任何帮助。
You have no public getters for your UpdateResult, for example :您的 UpdateResult 没有公共 getter,例如:
public static class UploadResult {
private String value;
public UploadResult(final String value)
{
this.value = value;
}
public String getValue() {
return this.value;
}
}
I believe by default auto discovery is on and will try to discover your getters.我相信默认情况下自动发现是开启的,并且会尝试发现你的吸气剂。 You can disable it with
@JsonAutoDetect(getterVisibility=Visibility.NONE)
, and in your example will result in []
.您可以使用
@JsonAutoDetect(getterVisibility=Visibility.NONE)
禁用它,并且在您的示例中将导致[]
。
I had a similar error using spring/jhipster
RESTful service (via Postman
)我在使用
spring/jhipster
RESTful 服务时遇到了类似的错误(通过Postman
)
The endpoint was something like:端点类似于:
@RequestMapping(value = "/index-entries/{id}",
method = RequestMethod.GET,
produces = MediaType.APPLICATION_JSON_VALUE)
@Timed
public ResponseEntity<IndexEntry> getIndexEntry(@PathVariable Long id) {
I was attempting to call the restful
endpoint via Postman
with header Accept: text/plain
but I needed to use Accept: application/json
我试图通过
Postman
使用标头Accept: text/plain
调用restful
端点,但我需要使用Accept: application/json
I too was facing a similar issue.我也面临着类似的问题。 In my case the request path was accepting mail id as path variable, so the uri looked like /some/api/test@test.com
在我的情况下,请求路径接受邮件 ID 作为路径变量,所以 uri 看起来像 /some/api/test@test.com
And based on path, Spring determined the uri is to fetch some file with ".com" extension and was trying to use different media type for response then intended one.并且基于路径,Spring 确定 uri 是获取一些扩展名为“.com”的文件,并尝试使用不同的媒体类型进行响应,然后是预期的。 After making path variable into request param it worked for me.
在将路径变量转换为请求参数后,它对我有用。
If using @FeignClient, add eg如果使用@FeignClient,添加例如
produces = "application/json"
to the @RequestMapping annotation到 @RequestMapping 注释
如果您使用的是Lombok ,请确保它在您的响应模型类中有@Data 或 @Getter @Setter 之类的注释。
Add below dependency to your pom.xml
:将以下依赖项添加到您的
pom.xml
:
<dependency>
<groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-xml</artifactId>
<version>2.10.2</version>
</dependency>
I had this issue when accessing actuator.我在访问执行器时遇到了这个问题。 Putting following configuration class solved the issue:
放置以下配置类解决了这个问题:
@Configuration
@EnableWebMvc
public class MediaConverterConfiguration implements WebMvcConfigurer {
@Bean
public MappingJackson2HttpMessageConverter jacksonConverter() {
MappingJackson2HttpMessageConverter mc =
new MappingJackson2HttpMessageConverter();
List<MediaType> supportedMediaTypes =
new ArrayList<>(mc.getSupportedMediaTypes());
supportedMediaTypes
.add(MediaType.valueOf(MediaType.APPLICATION_JSON_VALUE));
supportedMediaTypes.add(
MediaType.valueOf("application/vnd.spring-boot.actuator.v2+json"));
mc.setSupportedMediaTypes(supportedMediaTypes);
return mc;
}
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
converters.add(jacksonConverter());
}
}
My return object didn't have @XmlRootElement annotation on the class.我的返回对象在类上没有 @XmlRootElement 注释。 Adding the annotation solved my issue.
添加注释解决了我的问题。
@XmlRootElement(name = "ReturnObjectClass")
public class ReturnObjectClass {
@XmlElement(name = "Status", required = true)
protected StatusType status;
//...
}
I got the exact same problem.我遇到了完全相同的问题。 After viewing this reference: https://zetcode.com/springboot/requestparam/
查看此参考后: https ://zetcode.com/springboot/requestparam/
My problem solved by changing我的问题通过改变解决了
method = RequestMethod.GET, produces = "application/json;charset=UTF-8"
to至
method = RequestMethod.GET, produces = MediaType.TEXT_PLAIN_VALUE
and don't forget to add the library:并且不要忘记添加库:
import org.springframework.http.MediaType;
it works on both postman or regular browser.它适用于邮递员或常规浏览器。
Even if you do all of the above, as like in my case I still got the error 406 - Not acceptable when used from postman.即使您执行了上述所有操作,就像我的情况一样,我仍然收到错误 406 - 从邮递员使用时不可接受。 Upon careful study, I have noticed that, in the request headers, default header for 'accept' is ' / '.
经过仔细研究,我注意到,在请求标头中,“接受”的默认标头是“ / ”。
I solved my problem, by adding a preset to the header and switched off default header.我通过在标题中添加预设并关闭默认标题来解决我的问题。 Please see below screenshot.
请看下面的截图。
This solved my problem without any other settings or even adding the spring configurations.这解决了我的问题,没有任何其他设置,甚至没有添加弹簧配置。
In my case I was sending in correct object in ResponseEntity<>().就我而言,我在 ResponseEntity<>() 中发送了正确的对象。
Correct :正确的 :
@PostMapping(value = "/get-customer-details", produces = { MediaType.APPLICATION_JSON_VALUE })
public ResponseEntity<?> getCustomerDetails(@RequestBody String requestMessage) throws JSONException {
JSONObject jsonObject = new JSONObject();
jsonObject.put("customerId", "123");
jsonObject.put("mobileNumber", "XXX-XXX-XXXX");
return new ResponseEntity<>(jsonObject.toString(), HttpStatus.OK);
}
Incorrect :不正确:
return new ResponseEntity<>(jsonObject, HttpStatus.OK);
Because, jsonObject's toString() method "Encodes the jsonObject as a compact JSON string".因为,jsonObject 的 toString() 方法“将 jsonObject 编码为紧凑的 JSON 字符串”。 Therefore, Spring returns json string directly without any further serialization.
因此,Spring 直接返回 json 字符串,无需任何进一步的序列化。
When we send jsonObject instead, Spring tries to serialize it based on produces method used in RequestMapping and fails due to it "Could not find acceptable representation".当我们改为发送 jsonObject 时,Spring 会尝试基于 RequestMapping 中使用的 producer 方法对其进行序列化,但由于“找不到可接受的表示”而失败。
I had to explicitly call out the dependency for my json library in my POM.我必须在我的 POM 中显式调用我的 json 库的依赖项。
Once I added the below dependency, it all worked.一旦我添加了以下依赖项,这一切都奏效了。
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
</dependency>
就我而言,我碰巧正在使用 lombok,显然与 get 和 set 存在冲突
I had the same exception.我也有同样的例外。 The problem was, that I used the annotation
问题是,我使用了注释
@RepositoryRestController
instead of代替
@RestController
Add @Data annotation over the pojo class which you want to deserialize. 在要反序列化的pojo类上添加@Data注释。 The issue is solved for me :)
问题解决了我:)
For example, 例如,
import lombok.Data;
@Data
public class Response {
private Integer status;
private String type;
}
当我的一个控制器使用空@GetMapping
拦截所有请求时遇到了类似的问题
For me, the problem was trying to pass a filename in a url, with a dot.对我来说,问题是试图在 url 中传递一个带点的文件名。 For example
例如
"http://localhost:8080/something/asdf.jpg" //causes error because of '.jpg'
It could be solved by not passing the .jpg extension, or sending it all in a request body.它可以通过不传递 .jpg 扩展名或将其全部发送到请求正文中来解决。
I was running into the same issue, and what I was missing in my setup was including this in my maven (pom.xml) file.我遇到了同样的问题,我在设置中缺少的是将它包含在我的 maven (pom.xml) 文件中。
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>1.9.9</version>
</dependency>
if you are using postman to test, trying to check out the Header.如果您使用邮递员进行测试,请尝试签出标题。 my mistake was I'm using application/xml instead of application/json in "Accept" row.
我的错误是我在“接受”行中使用 application/xml 而不是 application/json。
Spent the whole day on this because none of the suggestions worked for me.花了一整天的时间,因为没有一个建议对我有用。 Alas, it was the
WebConfig
implementation; las,这是
WebConfig
的实现; specifically the configurer.ignoreAcceptHeader(true)
that was the culprit preventing the .yaml
from generating.特别是
configurer.ignoreAcceptHeader(true)
是阻止.yaml
生成的罪魁祸首。
Hope this helps someone.希望这对某人有帮助。
I encountered same exception: "Resolved [org.springframework.web.HttpMediaTypeNotAcceptableException: Could not find acceptable representation"]我遇到了同样的异常:“已解决[org.springframework.web.HttpMediaTypeNotAcceptableException:找不到可接受的表示”]
In analysis I fount that this problem can generate during serialization of a class while calling a @Controller or @RestController.在分析中,我发现这个问题可能在调用 @Controller 或 @RestController 时序列化 class 时产生。
In serialization, if you are using class, it must have public Setter and Getter .在序列化中,如果你使用 class,它必须有 public Setter 和 Getter 。
In the project where it occurs I found that a getter method was private and because of that this problem occurred.在它发生的项目中,我发现一个 getter 方法是私有的,因此发生了这个问题。
accepted answer is not right with Spring 5. try changing your URL of your web service to .json! Spring 5 接受的答案不正确。尝试将 Web 服务的 URL 更改为 .json! that is the right fix.
这是正确的解决方法。 great details here http://stick2code.blogspot.com/2014/03/solved-orgspringframeworkwebhttpmediaty.html
这里有很多细节http://stick2code.blogspot.com/2014/03/solved-orgspringframeworkwebhttpmediaty.html
I had the same exception but the cause was different and I couldn't find any info on that so I will post it here.我有同样的例外,但原因不同,我找不到任何信息,所以我会在这里发布。 It was just a simple to overlook mistake.
这只是一个容易忽略的错误。
Bad:坏的:
@RestController(value = "/api/connection")
Good:好的:
@RestController
@RequestMapping(value = "/api/connection")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.