-->

“Content type 'application/json;charset=UTF-8&

2020-08-10 08:13发布

问题:

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

{
    "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/"
}

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.

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

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 :

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;
    }
}

回答1:

I was able to solve it by removing @JsonManagedReference.



回答2:

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

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

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



回答3:

You can try something like

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



回答4:

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



回答5:

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.



回答6:

You can use "application/json" instead



回答7:

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

You can check that restapi for more informations.