$.ajax訪問RESTful Web Service報錯:Unsupported Media Type

來源:互聯網
上載者:User

標籤:unsupported media ty   ajax contenttype   

最近在項目中,前台頁面使用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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.