GET/POST Requst to REST API using Spring Boot

前端 未结 4 1232
北海茫月
北海茫月 2021-01-07 08:01

I have a REST Service an external server like https://api.myrestservice.com and I have a Spring Boot Application running locally on http://localhost:8080<

4条回答
  •  情书的邮戳
    2021-01-07 08:23

    Making post Api call from your code to another server:

    suppose you have a server https://searchEmployee... which returns you list of employees belonging to a particular city or belonging to a particular organization:

    request body:

    { 
    "city" : "Ranchi",
    "organisation" : "Bank Of America" 
    }
    

    json response: [{"name": "Vikash"},{"name":"kumar" },{}...etc]

    Then to make a post api call you can use RestTemplate in java like this:

    public void makeApiCall(){ 
        final String uri = "https://searchEmployee...";
    
        RestTemplate restTemplate = new RestTemplate();
    
        String reqBody = "{"city": "Ranchi"}";
        String result = restTemplate.postForObject(uri, reqBody, String.class);
    
        // convert your result into json
    
        try {
                    jsonResponse = new JSONObject(result);
            } catch (JSONException e) {
                e.printStackTrace();
            }
       //extract a value "name" from your json data:
       try{
        String value = jsonResponse.getString("name");  
        }catch(JSONException e) {
                e.printStackTrace();
            }
    }
    

    /********************************************************************/

    if you have more than one request body parameters to set do it like this:

    String reqBody = "{\"quantity\":100,\"name\":\"product1\",\"ifBoolean\":false}";
    

    false is a boolean value here in your request body and 100 is an integer.

    NOTE if you are having problem in setting request body copy it directly from postman request body and paste it inside double quote.

提交回复
热议问题