簡體   English   中英

Java Jersey Web 服務:使用 JSON 請求

[英]Java Jersey Web Service: consume JSON request

我有一個用 Java 和 Jersey 制作的網絡服務。 我想接收一個 JSON 請求並解析 json 以將存儲在 json 上的值保存在數據庫中。

這是小米網絡服務代碼:

@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"}

這是我的網絡標簽:

在此處輸入圖片說明

如果沒有進一步的配置, 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你可以查看這篇文章

也可以看看:

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM