【问题标题】:Java Jersey Web Service: consume JSON requestJava Jersey Web 服务:使用 JSON 请求
【发布时间】:2017-01-08 01:36:39
【问题描述】:

我有一个使用 Java 和 Jersey 制作的 Web 服务。我想接收一个 JSON 请求并解析 json 以保存数据库上 json 中存储的值。

这是mi web服务代码:

@Path("companies")
public class Companies {

    @Path("add")
    @POST
    @Produces(MediaType.APPLICATION_JSON)
    @Consumes(MediaType.APPLICATION_JSON)
    public JSONObject addCompanies(JSONObject inputJsonObj){

        String input = (String) inputJsonObj.get("company");
        String output = "The input you sent is :" + input;
        JSONObject outputJsonObj = new JSONObject();
        outputJsonObj.put("output", output);

        return outputJsonObj;
    }
}

客户端是用AngularJS制作的:

$scope.company = "";
    $scope.submit = function(){
        // Writing it to the server
        //      
        var dataObj = {
                company : $scope.company
        };  
        var res = $http.post('http://localhost:8080/WS-Test2/crunchify/companies/add', dataObj);
        res.success(function(data, status, headers, config) {
            $scope.message = data;
            notify("succes");
        });
        res.error(function(data, status, headers, config) {
            //alert( "failure message: " + JSON.stringify({data: data}));
            notify("fail");
        });
    };

这是我将 JSON 传递给 Web 服务时遇到的错误:

Status Code:415

这是我发送的请求:

{"company":"Testing2"}

这是我的网络标签:

【问题讨论】:

  • mm 看起来很奇怪..我对错误代码 415 做了一些研究..看起来格式不受支持..所以..你确定你是如何设置 json你的后端 api 的类型?可能使用 @Consumes ({MediaType.APPLICATION_JSON, MediaType.APPLICATION_JSON}) 之类的东西
  • 我尝试使用 @Consumes ({MediaType.APPLICATION_JSON, MediaType.APPLICATION_JSON}) 但我遇到了同样的错误
  • mm 看起来很奇怪,因为 Angular $http.post 发送默认 json ......所以我猜问题出在后端配置中......但我不知道 java :-)跨度>
  • 转到您的浏览器的开发人员工具网络选项卡,然后单击相应的服务调用。拍摄屏幕截图并更新您的问题。
  • @Aravind 我发布了

标签: java angularjs json rest jersey


【解决方案1】:

如果没有进一步的配置,JSONObject 不是 Jersey 支持的。您只需要使用字符串

public String addCompanies(String json){
    JSONObject inputJsonObj = new JSONObject(json)

    String input = (String) inputJsonObj.get("company");
    String output = "The input you sent is :" + input;
    JSONObject outputJsonObj = new JSONObject();
    outputJsonObj.put("output", output);

    return outputJsonObj.toString();
}

如果你真的想使用JSONObject,可以查看this post

另请参阅:

【讨论】:

  • 是的,我会检查 JAX-RS Entity Providers 的帖子来实现它。谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-01-01
  • 1970-01-01
  • 2012-09-24
  • 1970-01-01
  • 2012-04-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多