我在Spring中定义了一个REST服务,如下所示:
@RequestMapping(value = "/create", method = RequestMethod.POST)
@ResponseBody
public ResponseEntity<String> addArticle(@RequestBody Article article){
try{
articleService.addArticle(article.getTitle(),
article.getContent(),
article.getTags(),
article.getPublishStatus(),
article.getCompanyId(),
article.getCategory());
return new ResponseEntity<String>(HttpStatus.OK);
} catch (Exception e){
e.printStackTrace();
return new ResponseEntity<String>(e.getMessage(), HttpStatus.OK);
}
}
我的文章定义如下:
public class Article {
private int id;
private String title;
private String content;
private String smsContent;
public String getSmsContent()
{
return smsContent;
}
public void setSmsContent(String smsContent)
{
this.smsContent = smsContent;
}
private String[] tags;
private int companyId;
private String category;
public String getCategory(){
return category;
}
public void setCategory(String category){
this.category = category;
}
private byte publishStatus;
public String getTitle(){
return title;
}
public void setTitle(String title){
this.title = title;
}
public String getContent(){
return content;
}
public void setContent(String content){
this.content = content;
}
public String[] getTags(){
return tags;
}
public void setTags(String[] tags){
this.tags = tags;
}
public int getCompanyId(){
return companyId;
}
public void setCompanyId(int companyId){
this.companyId = companyId;
}
public byte getPublishStatus(){
return publishStatus;
}
public void setPublishStatus(byte publishStatus){
this.publishStatus = publishStatus;
}
public int getId(){
return id;
}
public void setId(int id){
this.id = id;
}
}
如何使用Angular调用此服务?我尝试了以下代码:
function createArticle(name, companyId, title, content, tags, category) {
var request = $http({
method : 'POST',
url : '/inbound/api/article/create.json',
headers : {
'Content-Type' : 'application/x-www-form-urlencoded'
},
transformRequest : function(obj) {
var str = [];
for ( var p in obj)
str.push(encodeURIComponent(p) + "="
+ encodeURIComponent(obj[p]));
return str.join("&");
},
data : {
title : title,
content : content,
tags : tags,
companyId : companyId,
category: category
}
});
我收到错误415 (Unsupported Media Type)
。有什么想法吗?
答案 0 :(得分:1)
由于您正在使用JSON,因此需要相应地设置表单和处理程序。
REST处理程序
@RequestMapping(value = "/create", method = RequestMethod.POST, consumes = "application/json")
角
headers : {
'Content-Type' : 'application/json'
},
答案 1 :(得分:1)
<强>第一强>
你有:@RequestMapping(value = "/create", method = RequestMethod.POST)
只是/create
<强>第二强>
你有:
url : '/inbound/api/article/create.json',
继续删除问题所在的.json
<强>第三强>
请务必指明ajax事件,您发送的数据是否为JSON