获取 HTTP 状态 415 - Jersey 不支持的媒体类型

Getting HTTP Status 415 - Unsupported Media Type with Jersey

下面是我的POJOclass

public class Credentials {
private int cred_id;
private String cred_user_name;
private String cred_password;
private String cred_token;

public Credentials(int cred_id, String cred_user_name,
        String cred_password, String cred_token) {
    this.cred_id = cred_id;
    this.cred_user_name = cred_user_name;
    this.cred_password = cred_password;
    this.cred_token = cred_token;
}

public int getCred_id() {
    return cred_id;
}

public void setCred_id(int cred_id) {
    this.cred_id = cred_id;
}

public String getCred_user_name() {
    return cred_user_name;
}

public void setCred_user_name(String cred_user_name) {
    this.cred_user_name = cred_user_name;
}

public String getCred_password() {
    return cred_password;
}

public void setCred_password(String cred_password) {
    this.cred_password = cred_password;
}

public String getCred_token() {
    return cred_token;
}

public void setCred_token(String cred_token) {
    this.cred_token = cred_token;
}

}

下面是我的资源class

public class ValidateUser {
@POST
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public String validateUser(Credentials credentials) {
    System.out.println("Going to validate the user" + credentials);
    String username = credentials.getCred_user_name();
    String password = credentials.getCred_password();
    CredentialsAccessor ca = new CredentialsAccessor();
    long count = 0;
    count = ca.authenticateUser(username, password);
    if (count > 0) {
        JSONObject jObject = new JSONObject();
        try {
            jObject.put("valid", "true");
            return jObject.toString();
        } catch (JSONException e) {
            e.printStackTrace();
            return "{'valid':'error'}";
        }
    } else {
        JSONObject jObject = new JSONObject();
        try {
            jObject.put("valid", "false");
            return jObject.toString();
        } catch (JSONException e) {
            e.printStackTrace();
            return "{'valid':'error'}";
        }
    }
}

}

Please see the maven dependencies here

我确保在 RESTClient 中我将内容类型指定为 Content-Type:application/json

Please see the RESTClient

下面是我的web.xml

但即便如此,我仍收到错误“获取 HTTP 状态 415 - 不支持的媒体

你能想象一下,我哪里错了吗?

我看到你有 MOXy。但是 MOXy 只知道如何处理用 @XmlRootElement 注释的 classes。这就是 415 的原因:Jersey 找不到 MessageBodyReader 来处理类型。

Credentials class 之上添加 @XmlRootElement 后,您将收到另一个错误,因为 MOXy 将无法实际反序列化 JSON 到您的 Credentials。原因是没有默认(无参数)构造函数。所以加上那个,我想你应该很好。