Java Spring Rest 应用程序中的“不支持内容类型‘application/json;charset=UTF-8’”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/50563593/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 23:41:08  来源:igfitidea点击:

"Content type 'application/json;charset=UTF-8' not supported" in Spring Rest application

javaspringresthttprequestpostman

提问by Ouissal

When I do a POST request on localhost:8080/api/usersto create a new user I get the following error :

当我在localhost:8080/api/users上执行 POST 请求以创建新用户时,出现以下错误:

{
    "timestamp": "2018-05-28T09:44:55.704+0000",
    "status": 415,
    "error": "Unsupported Media Type",
    "message": "Content type 'application/json;charset=UTF-8' not supported",
    "path": "/api/users/"
}

enter image description here

在此处输入图片说明

The is the request's body, JSON (application/json) is selected. It gives the same error even if I remove the Roles and keep it null.

是请求的正文,选择了 JSON (application/json)。即使我删除角色并将其保留为空,它也会出现相同的错误。

enter image description here

在此处输入图片说明

The header's content type is application/json as well.

标头的内容类型也是 application/json。

enter image description here

在此处输入图片说明

This is my controller :

这是我的控制器:

@PostMapping("/api/users" )
public User createUser(@Valid @RequestBody User user) {
    securityService.autologin(user.getUsername(), user.getPassword());
    return userService.createUser(user);
}

createUser function in UserService :

UserService 中的 createUser 函数:

public User createUser(@Valid @RequestBody User user) {
    user.setPassword(bCryptPasswordEncoder.encode(user.getPassword()));
    user.setRoles(new HashSet<>(roleRepository.findAll()));
    return userRepository.save(user);
}


edit

编辑

This is my User class :

这是我的用户类:

@Entity
@Table(name = "user")
@EntityListeners(AuditingEntityListener.class)
@JsonIgnoreProperties(value = {"createdAt", "updatedAt"}, 
                      allowGetters = true)
public class User implements Serializable{

    private static final long serialVersionUID = 1L;


    public User() {
        super();
        // TODO Auto-generated constructor stub
    }

    @Id
    @Column(name = "user_id")
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private long id;

    @Column(name = "user_name")
    private String name;

    @Column(name = "user_email")
    private String email;

    @Column(name = "user_password")
    @NotBlank
    private String password;

    @Column(name = "user_status")
    private String status;

    @Column(name = "user_tel")
    private String tel;

    @Column(name = "user_confirmation")
    private String confirmation;

    @Column(name = "user_birth_date")
    @Temporal(TemporalType.DATE)
    private Date birth_date;

    @Column(nullable = false, updatable = false)
    @Temporal(TemporalType.TIMESTAMP)
    @CreatedDate
    private Date createdAt;

    @Column(nullable = false)
    @Temporal(TemporalType.TIMESTAMP)
    @LastModifiedDate
    private Date updatedAt;

    @JsonManagedReference
    @ManyToMany
    @JoinTable(name = "user_role", joinColumns = @JoinColumn(name = "user_id"), inverseJoinColumns = @JoinColumn(name = "role_id"))
    private Set<Role> roles;

    @Column(name = "username")
    @NotBlank
    private String username;

    public long getId() {
        return id;
    }

    public void setId(long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getStatus() {
        return status;
    }

    public void setStatus(String status) {
        this.status = status;
    }

    public String getTel() {
        return tel;
    }

    public void setTel(String tel) {
        this.tel = tel;
    }

    public String getConfirmation() {
        return confirmation;
    }

    public void setConfirmation(String confirmation) {
        this.confirmation = confirmation;
    }

    public Date getBirth_date() {
        return birth_date;
    }

    public void setBirth_date(Date birth_date) {
        this.birth_date = birth_date;
    }

    public Date getCreatedAt() {
        return createdAt;
    }

    public Date getUpdatedAt() {
        return updatedAt;
    }

    public void setUpdatedAt(Date updatedAt) {
        this.updatedAt = updatedAt;
    }

    public Set<Role> getRoles() {
        return roles;
    }

    public void setRoles(Set<Role> roles) {
        this.roles = roles;
    }
}

采纳答案by Ouissal

I was able to solve it by removing @JsonManagedReference .

我能够通过删除 @JsonManagedReference 来解决它。

回答by Tryliom

Set @Produces(MediaType.APPLICATION_JSON)to your function to set it in json mime type.

设置@Produces(MediaType.APPLICATION_JSON)为您的函数以将其设置为 json mime 类型。

You can check that restapifor more informations.

您可以查看该 restapi以获取更多信息。

回答by Sajan Chandran

You can try something like

你可以尝试类似的东西

@PostMapping(value="/rest/account/json", consumes={"application/json"})

@PostMapping(value="/rest/account/json", consumes={"application/json"})

回答by Respect Pub

You specified content-type = application/json. I think you may have to check also "Accept" Header property (application/json)

您指定了 content-type = application/json。我认为您可能还需要检查“接受”标题属性(应用程序/json)

postman screenshot

邮递员截图

回答by Chandan Kumar

It clearly says Unsupported Media type which means due to any issue the call to operation cannot be completed. so check what your service operation is asking for and are you sending all the fields correctly. Most of the time there is mapping issue. Check console for errors.

它清楚地表明不受支持的媒体类型,这意味着由于任何问题,无法完成对操作的调用。因此,请检查您的服务操作要求什么,以及您是否正确发送了所有字段。大多数时候存在映射问题。检查控制台是否有错误。

回答by Himadri Mandal

You can use "application/json" instead

您可以改用“应用程序/json”

enter image description here

在此处输入图片说明

回答by Klaudia

In my case there was a Hymanson fail, logged as a WARN:

在我的情况下,Hymanson 失败,记录为警告:

Failed to evaluate Hymanson deserialization for type [[simple type, class ***]]: com.fasterxml.Hymanson.databind.JsonMappingException: Conflicting setter definitions for property [...]

Failed to evaluate Hymanson deserialization for type [[simple type, class ***]]: com.fasterxml.Hymanson.databind.JsonMappingException: Conflicting setter definitions for property [...]

I had overloaded a setter by accident, so it could not be resolved by Hymanson and spring has thrown 415.

我不小心超载了一个二传手,所以Hyman逊无法解决它,春天抛出了 415。