在本文中,我们将为您详细介绍SpringREST,JSON“无法处理托管/反向引用'defaultReference'”415不支持的媒体类型的相关知识,此外,我们还会提供一些关于415SpringM
在本文中,我们将为您详细介绍Spring REST,JSON“无法处理托管/反向引用'defaultReference'” 415不支持的媒体类型的相关知识,此外,我们还会提供一些关于415 Spring MVC和Rest Service不支持的媒体类型、415不支持的媒体类型-lightswitch 2012中的POST json到OData服务、415不支持的媒体类型; Angular2到API、415不支持的媒体类型jQuery Ajax的有用信息。
本文目录一览:- Spring REST,JSON“无法处理托管/反向引用'defaultReference'” 415不支持的媒体类型
- 415 Spring MVC和Rest Service不支持的媒体类型
- 415不支持的媒体类型-lightswitch 2012中的POST json到OData服务
- 415不支持的媒体类型; Angular2到API
- 415不支持的媒体类型jQuery Ajax
Spring REST,JSON“无法处理托管/反向引用'defaultReference'” 415不支持的媒体类型
如何解决Spring REST,JSON“无法处理托管/反向引用''defaultReference''” 415不支持的媒体类型?
我通过摆脱JsonManagedReference和JsonBackReference并将其替换为JsonIdentityInfo来解决了
解决方法
我试图使用Spring Boot / Spring RestController后端从AngularJS前端发布到http://
localhost:9095 / translators。
我可以执行GET,响应如下:
[{"userId":1,"firstName":"John","lastName":"Doe","emailId":"john.doe@inc.com","languages":[{"languageId":1,"languageCode":"gb","source":true}],"translations":[{"translationId":3,"sourceId":1,"sourceText":"Hello","targetId":null,"targetText":null,"translationStatus":"DUE"}],"userType":"TRANSLATOR"}
当我发布下面的json时,我得到了 错误 响应
发布数据:
{
firstName: "zen",lastName: "cv",emailId: "email",userType: "TRANSLATOR",languages : [{languageId:1,languageCode:"gb",source:true}]
}
错误:
{
timestamp: 1422389312497
status: 415
error: "Unsupported Media Type"
exception: "org.springframework.web.HttpMediaTypeNotSupportedException"
message: "Content type ''application/json'' not supported"
path: "/translators"
}
我确保我的控制器具有正确的Mediatype批注。
@RestController
@RequestMapping("/translators")
public class TranslatorController {
@Autowired
private UserRepository repository;
@RequestMapping(method = RequestMethod.GET)
public List findUsers() {
return repository.findAll();
}
@RequestMapping(value = "/{userId}",method = RequestMethod.GET)
public User findUser(@PathVariable Long userId) {
return repository.findOne(userId);
}
@RequestMapping(method = RequestMethod.POST,consumes = MediaType.APPLICATION_JSON_VALUE,produces = MediaType.APPLICATION_JSON_VALUE)
public User addTranslator(@RequestBody User user) {
//translation.setTranslationId(null);
return repository.saveAndFlush(user);
}
@RequestMapping(value = "/{translatorId}",method = RequestMethod.PUT)
public User updateTranslation(@RequestBody User updatedUser,@PathVariable Long userId) {
//updatedTranslation.setTranslationId(translationId);
return repository.saveAndFlush(updatedUser);
}
@RequestMapping(value = "/{translatorId}",method = RequestMethod.DELETE)
public void deleteTranslation(@PathVariable Long translationId) {
repository.delete(translationId);
}
}
经过一些研究并通过查看日志输出,我意识到这是一个误导性的错误消息,并且实际上在序列化/反序列化Json时发生了问题
在日志文件中,我发现
2015-01-27 21:08:32.488 WARN 15152 — [nio-9095-exec-1]
.cjMappingJackson2HttpMessageConverter:无法评估类型[简单类型,类用户]的反序列化:java.lang.IllegalArgumentException:无法处理托管/反向引用’defaultReference’:反向引用类型(java.util.List)与托管类型(User)不兼容
这是我的类User和Class Translation(为简洁起见,省略了getter,setter,构造函数等)
@Entity
@Table(name = "users")
public class User {
@Id
@GeneratedValue(strategy= GenerationType.AUTO)
@Column(name = "user_id")
private long userId;
@Column(name = "first_name")
private String firstName;
@Column(name = "last_name")
private String lastName;
@Column(name = "email_id")
private String emailId;
@ManyToMany
@JoinTable(name = "languages_users",joinColumns = { @JoinColumn(name = "user_id")},inverseJoinColumns = {@JoinColumn(name = "lang_id")})
@JsonManagedReference
private List<Language> languages = new ArrayList<Language>();
@OneToMany(mappedBy = "translator",fetch = FetchType.EAGER)
@JsonManagedReference
private List<Translation> translations;
@Enumerated(EnumType.STRING)
private UserType userType;
}
@Entity
@Table(name = "translations")
public class Translation {
@Id
@GeneratedValue(strategy= GenerationType.IDENTITY)
@Column(name = "translation_id")
private Long translationId;
@Column(name = "source_lang_id")
private Long sourceId;
@Column(name = "source_text")
private String sourceText;
@Column(name = "target_lang_id")
private Long targetId;
@Column(name = "target_text")
private String targetText;
@Enumerated(EnumType.STRING)
@Column(name = "status")
private TranslationStatus translationStatus;
@ManyToOne
@JoinColumn(name = "translator_id")
@JsonBackReference
private User translator;
}
我的问题是:如何为上述实体正确设置JsonManagedReference和JsonBackReference?我确实读过文档。而且我无法根据错误消息找出问题所在
415 Spring MVC和Rest Service不支持的媒体类型
我正进入(状态
415 Unsupported Media Type - The server refused this request because the request entity is in a format not supported by the requested resource for the requested method
请求网址为:
http://localhost:8080/ngdemo/web/posts/review/80a5d7660cdb82a8ef9f8db79bb3c8ab14555377
从弹簧控制器读取时出错;我检查了其他具有相同模式的控制器方法,它们工作正常,但不是我新介绍的这种方法。我找不到任何问题,能否请您提出我所缺少的内容?
我的控制器:
@RequestMapping(value = "/review/{key}",method = RequestMethod.GET,consumes = "",produces = "application/json")
public
@ResponseBody
List<Review> reviews(@PathVariable(value = "key") String key) {
System.out.println("key : " + key);
List<Review> reviewList = reviewService.getReviewsById(key);
System.out.println("reviewList : " + reviewList.size());
return reviewList;
}
我的Angular Services.js:
services.factory('PostFactory',['$resource',function ($resource) {
alert("I am here service");
return {
postmain: $resource('/ngdemo/web/posts',{},{
query: {method: 'GET',isArray: true },create: {method: 'POST'}
}),reviews: $resource('/ngdemo/web/posts/review/:key',params: {key: '@key'} },postreview: $resource('/ngdemo/web/posts/getreview',allresults: $resource('/ngdemo/web/posts/result/:tag',params: {tag: '@tag'} },create: {method: 'POST'}
})};
}]);
我的controller.js中的代码可以调用:
var reviewId = place.id;
$scope.allreviews = PostFactory.reviews.query({key: reviewId})
我找不到问题出在哪里,所以请大家看看并指出我想念的是什么?谢谢!
415不支持的媒体类型-lightswitch 2012中的POST json到OData服务
使用JSON发布到OData服务时,出现“错误415:不支持的媒体类型”。
解决方案位于此较长文章的底部。
我可以使用JSON进行获取,但是一旦尝试POST,我就会收到此错误。
我也可以使用XML进行GET / POST,但是我需要使用json。
我认为此错误是指我的标头中的某些内容,而不是我的请求正文的json格式(在下面也可能是错误的),我尝试了多种变体导致相同的错误。
我一直在尝试使用Fiddler进行调试,以下是结果。
JSON开机自检
请求
POST http://scdb38:8888/bi.test/applicationdata.svc/Sharks HTTP/1.1User-Agent: FiddlerHost: scdb38:8888Content-Length: 91Accept: application/json;odata=verbose;Content-Type: application/json;{ "d":[ { "Name":"Great White ", "Food":"Surfers" } ]}
响应
HTTP/1.1 415 Unsupported Media TypeCache-Control: privateContent-Length: 186Content-Type: application/json;odata=verbose;charset=utf-8Server: Microsoft-IIS/7.5X-Content-Type-Options: nosniffDataServiceVersion: 1.0;X-AspNet-Version: 4.0.30319X-Powered-By: ASP.NETDate: Wed, 16 Oct 2013 06:20:10 GMT{"error":{"code":"1","message":{"lang":"en-AU","value":"<?xml version=\"1.0\" encoding=\"utf-16\"?><ExceptionInfo><Message>Unsupported media type requested.</Message></ExceptionInfo>"}}}
JSON GET
请求标题
GET http://scdb38:8888/bi.test/applicationdata.svc/Sharks HTTP/1.1User-Agent: FiddlerHost: scdb38:8888Content-Length: 0Accept: application/json;odata=verbose;Content-Type: application/json;
响应头
HTTP/1.1 200 OKCache-Control: no-cacheContent-Length: 591Content-Type: application/json;odata=verbose;charset=utf-8Server: Microsoft-IIS/7.5X-Content-Type-Options: nosniffDataServiceVersion: 1.0;X-AspNet-Version: 4.0.30319X-Powered-By: ASP.NETDate: Wed, 16 Oct 2013 06:23:41 GMT{"d":[{"__metadata":{"id":"http://scdb38:8888/BI.Test/ApplicationData.svc/Sharks(1)","uri":"http://scdb38:8888/BI.Test/ApplicationData.svc/Sharks(1)","etag":"W/\"X''00000000000007E4''\"","type":"LightSwitchApplication.Shark"},"Id":1,"RowVersion":"AAAAAAAAB+Q=","Name":"Tiger Shark","Food":"Penguins"},{"__metadata":{"id":"http://scdb38:8888/BI.Test/ApplicationData.svc/Sharks(2)","uri":"http://scdb38:8888/BI.Test/ApplicationData.svc/Sharks(2)","etag":"W/\"X''00000000000007E5''\"","type":"LightSwitchApplication.Shark"},"Id":2,"RowVersion":"AAAAAAAAB+U=","Name":"Grey Nurse","Food":"Lettuce"}]}
我不太明白为什么GET可以正常工作时POST不支持媒体类型的原因。我意识到我正在使用DataServiceVersion:1.0并已查找升级,但是我正在使用LightSwitch
2012并在引用新版本时遇到问题,而又没有破坏LightSwitch应用程序。我认为LightSwitch
2013使用的是较新的版本(?),但是对我而言,升级带来了新的(非技术性)挑战。我感觉自己正在绕过圈子,这是我的最后选择,与同事交谈后,我唯一的失败选择是在数据库上创建数据模型并在此数据库上创建OData服务。
-— 更新 -—
此后,我尝试了Jen S提供的两个修复程序,现在得到错误:400错误的请求。
使用odata = verbose
POST http://scdb38:8888/bi.test/applicationdata.svc/Sharks HTTP/1.1Accept: application/json;odata=verbose;Content-Type: application/json;odata=verbose;Content-Length: 98Host: scdb38:8888{ "d":[ { "Name":"Great White ", "Food":"Surfers" } ]}HTTP/1.1 400 Bad RequestCache-Control: privateContent-Length: 201Content-Type: application/json;odata=verbose;charset=utf-8Server: Microsoft-IIS/7.5X-Content-Type-Options: nosniffDataServiceVersion: 1.0;X-AspNet-Version: 4.0.30319X-Powered-By: ASP.NETDate: Wed, 16 Oct 2013 23:31:09 GMT{"error":{"code":"1","message":{"lang":"en-AU","value":"<?xml version=\"1.0\" encoding=\"utf-16\"?><ExceptionInfo><Message>An error occurred while processing this request.</Message></ExceptionInfo>"}}}
使用DataServiceVersion:1.0
POST http://scdb38:8888/bi.test/applicationdata.svc/Sharks HTTP/1.1Accept: application/json;odata=verbose;Content-Type: application/json;Content-Length: 98Host: scdb38:8888DataServiceVersion: 1.0;{ "d":[ { "Name":"Great White ", "Food":"Surfers" } ]}HTTP/1.1 400 Bad RequestCache-Control: privateContent-Length: 201Content-Type: application/json;odata=verbose;charset=utf-8Server: Microsoft-IIS/7.5X-Content-Type-Options: nosniffDataServiceVersion: 1.0;X-AspNet-Version: 4.0.30319X-Powered-By: ASP.NETDate: Wed, 16 Oct 2013 23:31:09 GMT{"error":{"code":"1","message":{"lang":"en-AU","value":"<?xml version=\"1.0\" encoding=\"utf-16\"?><ExceptionInfo><Message>An error occurred while processing this request.</Message></ExceptionInfo>"}}}
使用WebServiceVerion:2.0
POST http://scdb38:8888/bi.test/applicationdata.svc/Sharks HTTP/1.1Accept: application/json;odata=verbose;Content-Type: application/json;Content-Length: 98Host: scdb38:8888DataServiceVersion: 2.0;{ "d":[ { "Name":"Great White ", "Food":"Surfers" } ]}HTTP/1.1 400 Bad RequestCache-Control: privateContent-Length: 201Content-Type: application/json;odata=verbose;charset=utf-8Server: Microsoft-IIS/7.5X-Content-Type-Options: nosniffDataServiceVersion: 1.0;X-AspNet-Version: 4.0.30319X-Powered-By: ASP.NETDate: Wed, 16 Oct 2013 23:38:23 GMT{"error":{"code":"1","message":{"lang":"en-AU","value":"<?xml version=\"1.0\" encoding=\"utf-16\"?><ExceptionInfo><Message>An error occurred while processing this request.</Message></ExceptionInfo>"}}}
我是否正在解决这个问题,这仅仅是JSON请求主体结构不正确的问题吗?我尝试了几次尝试都没有成功,但是使用XML进行发布是可行的。
----- 解决方案 ------
感谢Jen的帮助,使用json格式向OData服务发布对我来说很有效。
POST http://scdb38:8888/bi.test/applicationdata.svc/Sharks HTTP/1.1Accept: application/json;odata=verbose;Content-Type: application/json;Content-Length: 62Host: scdb38:8888DataServiceVersion: 1.0; { "Name":"Great White ", "Food":"Surfers" }HTTP/1.1 201 CreatedCache-Control: no-cacheContent-Length: 298Content-Type: application/json;odata=verbose;charset=utf-8ETag: W/"X''00000000000007E7''"Location: http://scdb38:8888/BI.Test/ApplicationData.svc/Sharks(4)Server: Microsoft-IIS/7.5X-Content-Type-Options: nosniffDataServiceVersion: 1.0;X-AspNet-Version: 4.0.30319X-Powered-By: ASP.NETDate: Thu, 17 Oct 2013 23:22:12 GMT{"d":{"__metadata":{"id":"http://scdb38:8888/BI.Test/ApplicationData.svc/Sharks(4)","uri":"http://scdb38:8888/BI.Test/ApplicationData.svc/Sharks(4)","etag":"W/\"X''00000000000007E7''\"","type":"LightSwitchApplication.Shark"},"Id":4,"RowVersion":"AAAAAAAAB+c=","Name":"Great White ","Food":"Surfers"}}
答案1
小编典典看来此问题与Content-Type
和Accept
标头之间的差异有关。在HTTP中,Content-Type
用于请求和响应有效负载中以传达当前有效负载的媒体类型。Accept
在请求有效负载中使用来表示服务器可以在响应有效负载中使用的媒体类型。
因此,Content-Type
在没有正文的请求中(例如您的GET请求)没有任何意义。当您执行POST请求时,您正在发送消息正文,因此这很Content-Type
重要。
如果服务器无法处理Content-Type
请求的请求,它将返回415
HTTP错误。(如果服务器不能满足请求Accept
标头中的任何媒体类型,它将返回406错误。)
在OData v3中,媒体类型“ application / json”被解释为表示新的JSON格式(“ JSON
light”)。如果服务器不支持读取JSON light,则服务器在看到传入的请求是JSON
light时将抛出415错误。在有效负载中,您的请求正文是冗长的JSON,而不是JSON
light,因此服务器应该能够处理您的请求。但这并不是因为它看到了JSON light内容类型。
您可以通过以下两种方法之一来解决此问题:
- 在POST请求中将Content-Type设置为“ application / json; odata = verbose”,或者
- 在请求中包括DataServiceVersion标头,并将其设置为小于v3。例如:
DataServiceVersion: 2.0;
(选项2假定您在请求有效负载中未使用任何v3功能。)
415不支持的媒体类型; Angular2到API
当我尝试从角度2发布到API我得到 – 415不支持的媒体类型.
Angular 2代码:
onSubmit(value: any) { // console.log(value.message); let headers = new Headers({ 'Content-Type': 'application/json'}); let options = new RequestOptions({ headers: headers }); let creds = 'statusukNown'; let body = JSON.stringify(creds); this.http.post('http://localhost:1318/api/ActionItem',creds) .subscribe( () => {console.log('Success')},err => {console.error(err)} ); }
我的控制器代码:
// POST api/actionitem [HttpPost] public ActionItem Post( [FromBody]string str)// _id,string _status) { ActionItem item = new ActionItem( 313,str); return item; }
当我将控制器代码更改为不从主体获取数据时,它可以工作但是引用NULL.
我的API调用截图:
请帮助&如果需要更多细节,请告诉我.
解决方法
this.http.post('http://localhost:1318/api/ActionItem',body,options).map(response => response.json()) .subscribe( () => {console.log('Success')} );
415不支持的媒体类型jQuery Ajax
我正在使用Maven Rest API。通过jQuery Ajax调用发出POST请求时,出现415错误。请看一下我的代码。
function getUserDetails() { var name = $("#name").val(); var mobile = $("#mobile").val(); var location = $("#location").val(); var email = $("#email").val(); var userDetails = { "name": name, "mobile": mobile, "email": email, "location": location }; return userDetails;}function createuser() { sendRequest("registerProcess", getUserDetails(), "post");}function sendRequest(url, input, method) { $.ajax({ url: url, async: false, data: JSON.stringify(input), error: function(response) { //displayResponseMessage(response); console.log("Error"); }, success: function(response) { console.log(" Successfull"); }, type: method, headers: { Accept: ''application/json;charset=utf-8'', contentType: ''application/json;charset=utf-8'' }, dataType: ''json'' });}
这是我的控制器。这UserForm
是POJO类别
@RequestMapping(value = "/registerProcess", method = RequestMethod.POST,consumes= MediaType.APPLICATION_JSON_VALUE)public String addUser(@RequestBody UserForm user) { System.out.println("Inside Controller" ); String email = user.getEmail(); String mobile = user.getMobile(); System.out.println("Details :" + email + mobile); return "welcome";}
提前致谢
答案1
小编典典提供标头''Content-Type'' : ''application/json''
,此处输入是可以直接在ajax请求中发送的对象data :input
关于Spring REST,JSON“无法处理托管/反向引用'defaultReference'” 415不支持的媒体类型的问题就给大家分享到这里,感谢你花时间阅读本站内容,更多关于415 Spring MVC和Rest Service不支持的媒体类型、415不支持的媒体类型-lightswitch 2012中的POST json到OData服务、415不支持的媒体类型; Angular2到API、415不支持的媒体类型jQuery Ajax等相关知识的信息别忘了在本站进行查找喔。
本文标签: