有 Java 编程相关的问题?

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

javascript如何使用ajax通过post将json文件发送到使用api的java spring控制器

我一直试图通过post将一个json文件从ajax发送到我的控制器,在那里我正在使用一个api,但我无法得到答案

这是我的脚本,我有我的JSONObject

var jsonObjects = {
        "vehicle": {
            "id": "272",
            "year": "2017",
            "marketValue": {
                "amount": 345000,
                "currency": "MXN"
            }
        },
        "downPayment": {
            "amount": 34500,
            "currency": "MXN"
        },
        "installmentPlanTerms": {
            "number": "36",
            "frequency": "MONTHLY"
        },
        "casualtyInsurance": true,
        "lifeInsurance": false
    }; 

这是我的ajax,其中包括我的控制器的url

$.ajax({
    type: 'post',
    url: '/vehicle/cotizar',
    data: JSON.stringify(jsonObjects),
    contentType: "application/json; charset=utf-8",
    traditional: true,
    success: function (data) {
       //document.log(data.data.requestedAmount.amount);
    }
});

这是我在java spring中的控制器

@RequestMapping(value="/vehicle/cotizar")
    public String options(){
        HttpHeaders headers = new HttpHeaders();
        String token = "some key";
        headers.set("Authorization","jwt ".concat(token));
        headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
        HttpEntity<String> entity = new HttpEntity<String>(headers);
        return restTemplate.exchange("https://apis.bbvabancomer.com/loans_sbx/v1/options-installment", HttpMethod.POST, entity, String.class).getBody();
    }

我希望控制器返回我通过ajax生成的json结果 as you can see in the image i am using postman where i am sending a json file via post to api and the api return me an answer


共 (1) 个答案

  1. # 1 楼答案

    我已经解决了 在我的控制器中,我必须修改这个

    @RequestMapping(value="/vehicle/cotizar", method = RequestMethod.POST)
    @ResponseBody
    public String performLogin(@RequestBody String json, HttpServletRequest request, HttpServletResponse response) {
        HttpHeaders headers = new HttpHeaders();
        log.info("debugeo".concat(json));
        String token ="some key";
        headers.set("Authorization","jwt ".concat(token));
        //headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
        String a ="Content-Type";
        String b = "application/json";
        headers.set(a,b);
        HttpEntity<String> entity = new HttpEntity<String>(json,headers);
        log.info("con entity prueba".concat(entity.getBody()));
        return restTemplate.exchange("https://apis.bbvabancomer.com/loans_sbx/v1/options-installment", HttpMethod.POST, entity, String.class).getBody();
    }
    

    我得到了答案 1