0

How to send json data in request body through GET request to external API in Spring Boot application.

Akhilesh
  • 1
  • 7

2 Answers2

0

Simple answer, you can't send a body request using http GET verb.

If you are looking for a way to call external API by sending data in request body, you have the choice between restTemplate and webClient, prefer the latter if the external API is async.

Examples Using RestTemplate :

RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
BookModel book = new BookModel("effective java");
String bookAsJson = new ObjectMapper().writeValueAsString(book);
HttpEntity<String> request = new HttpEntity<String>(bookAsJson, headers);
String dataResult = restTemplate.postForObject("http://external-api-here/book", request, String.class);
Abdelghani Roussi
  • 2,707
  • 2
  • 21
  • 39
  • I am trying using resttemplate.exchange for GET but getting Bad request error is that body is not accepting by other API or can you please look on to this below question I have provided more details. https://stackoverflow.com/q/64683261/11478835 – Akhilesh Nov 05 '20 at 01:41
0

Please code might help. From "res" get your pojo.

import org.springframework.web.client.RestTemplate;
import com.google.gson.JsonObject;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;


RestTemplate restTemplate = new RestTemplate();
            
String url = "<external api url>";
            
JsonObject jsobObject=new JsonObject();
jsobObject.addProperty("someJsonProperty", "someJsonPropertyValue");
HttpHeaders headers=new HttpHeaders();
headers.add("Accept", MediaType.APPLICATION_JSON.toString());
headers.add("Content-Type",MediaType.APPLICATION_JSON.toString());
            
HttpEntity<String> httpEntity = new HttpEntity<>(jsobObject.toString(), headers);
            
String res = restTemplate.exchange(url, HttpMethod.GET, httpEntity, String.class).getBody();