我尝试发送 PUT 请求。我有serialazible类和具有必要设置的 Controller ,我的请求有contentType:“application/json”。

目的地航类:

 public class FlightDto implements Serializable { 
    private int id; 
    private String navigation; 
 
    public FlightDto() { 
        super(); 
    } 
 
    public int getId() { 
        return id; 
    } 
 
    public void setId(int id) { 
        this.id = id; 
    } 
 
    public String getNavigation() { 
        return navigation; 
    } 
 
    public void setNavigation(String navigation) { 
        this.navigation = navigation; 
    } 
 
} 

PUT 请求:

  function editNavigation() { 
    var flight={ 
        id:idAction.replace('edit',''), 
        navigation:newNavigation 
    }; 
    console.log(flight); 
    var prefix = '/airline/'; 
    $.ajax({ 
        type: 'PUT', 
        url: prefix +'flights/' + idAction.replace('edit',''), 
        data: JSON.stringify(flight), 
        contentType: "application/json", 
        success: function(receive) { 
            $("#adminTable").empty(); 
            $("#informationP").replaceWith(receive); 
            $("#hiddenLi").removeAttr('style'); 
        }, 
        error: function() { 
            alert('Error edited flight'); 
        } 
    }); 
} 

console.log(航类); - 对象{id:“7”,导航:“sdfdsfsd”}

飞行 Controller :

   @RequestMapping(value = prefix + "/flights/{id}", method = RequestMethod.PUT, consumes = MediaType.APPLICATION_JSON_VALUE) 
    @ResponseBody 
    public String updateFlight(@PathVariable("id") String id, @RequestBody FlightDto flightDto) { 
        String returnText = "Flight edited successful"; 
        String str1 = flightDto.getNavigation(); 
        String str2 = id; 
        return returnText; 
    } 

错误:

org.springframework.web.HttpMediaTypeNotSupportedException: Content type 'application/json' not supported 

如何修复这个错误?

请您参考如下方法:

您需要使用 headers 属性在 header 中而不是在有效负载中定义内容类型

   data: JSON.stringify(flight), 
   headers:{contentType: "application/json"} 


评论关闭
IT源码网

微信公众号号:IT虾米 (左侧二维码扫一扫)欢迎添加!