Guide to transmitting a JSON file through a POST request, utilizing Ajax to communicate with a Java Spring controller that is interfacing with an API

I've been attempting to send a JSON file through AJAX post to my controller for API consumption, but I haven't received any response.

Below is the script containing the JSON object:

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
    }; 

Here is the AJAX request where the controller URL is included:

$.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);
    }
});

Below is my Java Spring controller code:

@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();
    }

I'm hoping that the controller will return the JSON result I sent via AJAX. Refer to this image using Postman where I successfully sent a JSON file via POST to the API and received a response.

Answer №1

The issue has been successfully resolved I made necessary modifications in my controller as shown below:

@RequestMapping(value="/vehicle/cotizar", method = RequestMethod.POST)
@ResponseBody
public String performLogin(@RequestBody String json, HttpServletRequest request, HttpServletResponse response) {
    HttpHeaders headers = new HttpHeaders();
    log.info("debugging".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("with entity test".concat(entity.getBody()));
    return restTemplate.exchange("https://apis.bbvabancomer.com/loans_sbx/v1/options-installment", HttpMethod.POST, entity, String.class).getBody();
}

Now, I have received the desired response 1

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips for ensuring that the Java program only accepts positive values

I'm encountering an issue with the if/else statement in my program. The intention is for the program to reject negative values, but it doesn't exit the loop when a negative value is input. Here's a snippet of the code: try { System.out ...

Is there a reason why I can't load all Google charts on one webpage?

I am trying to use the Google Charts API to display various charts on my web page. However, I seem to be encountering an issue where the last chart is not loading correctly. Can someone point out what I might be missing in my code? I would greatly apprecia ...

Looping through MySQL data within a column in Datatables

Within my Datatables grid, I am fetching MySQL data using a server-side PHP script. My objective is to iterate inside each column of the table. For instance, consider the current display of my datatables with data selected from the 'tb order' tab ...

Having trouble with setTimeout causing the error "function is not defined"!

Issue with setTimeout showing "function is not defined" error! Can you identify the problem in the following code snippet? $(document).ready(function(){ function ISS_NextImage() { //ImageSlideShow NextImage $('.ImageSlideShow').each(functi ...

Incorrect use of key in encryption

Within this specific class, the process of encrypting data values begins by obtaining the cipher in the following manner: KeyStore primaryKeyStore = getKeyStore(keyStoreFile, password, keyType, provider); java.security.cert.Certificate certs = primaryKeyS ...

Creating dynamic drop-down menus using PHP, HTML, JavaScript, and MySQL

I need help with a form where users are required to select departments and based on that, the corresponding defect fields should populate with matching defects. Currently, when I try removing Defect 4, Defect 3 works; remove 4 & 3, then 2 works and so fo ...

When attempting to input a decimal number into a numerical text box, Firefox displays an error message

Here is the code for my numeric input field: <input type="number" id="payment-textbox" name="payment-textbox" min="1" max="100000" maxlength="9" class="payment" placeholder="--" value=""/> While this code functions properly in Google Chrome, I enco ...

Calculate the sum of a short and integer value, then assign the value to a short variable

When running the following code snippet, I received a result of -7615. Can someone please help me understand why? public static void main(String[] args) { short s = 1; int z=123456; s+=z; System.out.println(s); } ...

Retrieve information from an external JSON API using jQuery

I need help with reading JSON data using jQuery. I have tried the code below but it doesn't seem to be working. This is the link to my JSON file: and here is my code snippet: $.getJSON("http://goo.gl/PCy2th", function(data){ $.each(data.PlayList ...

ng-bootstrap's accordion imparts unique style to its child icons

https://i.sstatic.net/YzmtN.png Visible star icon indicates lack of focus on the accordion https://i.sstatic.net/aNW31.png Star disappears when accordion gains focus Below is the CSS code I used to position the star to the left of the accordion: .icon ...

What is the reasoning behind needing the method name to include "static" when using an ArrayList but returning a primitive type?

There is an aspect of this program that puzzles me - why do the methods using an ArrayList require the inclusion of static in the method header? To provide context, this program reads a text file, processes its contents, and stores them in an ArrayList< ...

Running the npm build command generates JavaScript that is not compatible with Internet Explorer

After executing npm run build, the generated JavaScript code looks like this: jQuery.extend({ propFix: { for: "htmlFor", class: "className" }, Unfortunately, this format is not compatible with several versions of Internet Explorer ...

Ensure the configuration is stored in a safe location where files cannot be accessed through external links

Currently, I am attempting to utilize a configuration file for both a database and rating script. However, the dilemma lies in the fact that the config file is located in this directory: website.com/include/config.php also known as websitename/include/co ...

Issues with the ASP.NET AJAX AutoComplete feature failing to trigger the code-behind functionality

(Before flagging this question as a duplicate, I have gone through all the other questions. However, most of them contain outdated links and do not address my particular issue) I am attempting to create a basic autocomplete feature, but the Code-Behind is ...

How can I change the URL parameter values in an Ajax request using HDIV?

I have been working on incorporating HDIV into my existing application, but I have hit a roadblock while trying to resolve the following issue. Scenario: 1. Within my application, there is a large form containing numerous fields. Whenever I modify a valu ...

Executing a function right away when it run is a trait of a React functional component

Having a fully functional React component with useState hooks, and an array containing five text input fields whose values are stored in the state within an array can be quite challenging. The main issue I am facing is that I need to update the inputfields ...

Retrieve IPv4 addresses of an ethernet adapter on a Windows machine utilizing Java version 1.5

Issue My Windows operating system is equipped with multiple Ethernet adapters. I am in need of a solution to determine the IP addresses associated with a specific Ethernet adapter. To illustrate, upon running the ipconfig command on my device, the follow ...

Error locating element using Java Selenium POM with HTML XPath: Element not found

I encountered an error while attempting to locate the web element for testing the Facebook "create a page" / "sign up" button within the Page Object Model. I have tried using different methods such as CSS selector by class name and even copying the syste ...

Having trouble with the input range slider on Chrome? No worries, it's working perfectly fine

I'm currently facing an issue with an input range slider that controls the position of an audio track. It seems to work perfectly in Firefox, but in Chrome, the slider gets stuck and doesn't move when dragged. There is a function in place that up ...

How to show multiline error messages in Materials-UI TextField

Currently, I am attempting to insert an error message into a textfield (utilizing materials UI) and I would like the error text to appear on multiple lines. Within my render method, I have the following: <TextField floatingLabelText={'Input Fi ...