首页 > 代码库 > $.ajax访问RESTful Web Service报错:Unsupported Media Type

$.ajax访问RESTful Web Service报错:Unsupported Media Type

最近在项目中,前台页面使用jquery ajax访问后台CXF发布的rest服务,结果遇到了错误"Unsupported Media Type"。

发布的服务java代码如下:

import javax.jws.WebService;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Response;

@WebService
@Produces({ "application/json" })
public class TrackService {
	@POST
	@Path("/trackInBatch/")
	@Consumes("application/json")
	public Response postTrackInfoInBatch(List<TrackPosition> positions) {
		return retrieve(positions, clientGen, trafficMapLayerId, projectParaLayerId, "0");
	}
}

 

调用服务的javascript代码如下:

$.ajax({
	url : "/myapp/rest/track/trackInBatch/",
	async:false,
	type : "POST",
	dataType:"json",
	data:[],
	error:function(XMLHttpRequest, textStatus, errorThrown){
		alert(errorThrown);
	},
	success: function(data, textStatus){
		outResponse = data;
	}		
});


调用的服务的时候报错:Unsupported Media Type。通过HttpWatch查看原始的request和response报文,发现返回request报文中的contentType是:application/x-www-form-urlencoded。查看jquery.ajax()的API文档,发现contentType的默认值就是:application/x-www-form-urlencoded。

 

但是后台发布的rest服务,@Consumes("application/json")要求request报文的contentType必须是application/json

手动设置contentType之后,发现问题解决。

$.ajax({
	url : "/myapp/rest/track/trackInBatch/",
	async:false,
	type : "POST",
	dataType:"json",
	contentType:"application/json",
	data:[],
	error:function(XMLHttpRequest, textStatus, errorThrown){
		alert(errorThrown);
	},
	success: function(data, textStatus){
		outResponse = data;
	}		
});


 

$.ajax访问RESTful Web Service报错:Unsupported Media Type