有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java我无法在post调用中获取JSONObject获取415

@POST
@Path("/sessions")
@Consumes("application/json")
@Produces("application/json")
public Response createSession(JSONObject jsonObject){

    if (jsonObject.get("subjectId").equals("amadmin")){
        jsonObject.put("username", jsonObject.get("subjectId"));
        jsonObject.put("password", jsonObject.get("authInfo"));
    }
    else{
        jsonObject.put("username", jsonObject.get("subjectId"));
        jsonObject.put("password", jsonObject.get("authInfo"));
        jsonObject.put("uri", "realm=" + jsonObject.get("realm"));
    }

    String openAmUrl = String.format("http://%s%s/identity/json/authenticate", 
            openAmIp, openAmWarName);

    URI uri = null;
    try {
        uri = new URI(openAmUrl);
    } 
    catch (URISyntaxException e) {
        LOGGER.error("Exception " + e);
    }
    return Response.seeOther(uri).build();
}

我试图用JSON字符串调用post调用,比如: {"subjectId":"me", "authInfo":"password"} 我总是得到HTTP/1.1 415 Unsupported Media Type。 我知道,如果我的方法正在接收JSONObject,那么帖子中的字符串将自动转换为JSONObject,但仍然会收到415错误,尽管我使用的标题是: 内容类型:application/json 接受:application/json

你能帮忙吗


共 (1) 个答案

  1. # 1 楼答案

    其实很简单,下面是新代码:

    POST
    @Path("/sessions")
    @Consumes("application/json")
    public Response createSession(String body){
    
        JSONObject jsonObject = null;
        try {
            jsonObject = new JSONObject(body);
        } catch (ParseException e) {
            LOGGER.error("This is not a valid JSON " + e);
            return Response.status(400).build();
        }