Post Json Array in Json Object via RestTemplate in Spring Boot - java

Im trying to post an array in a json object using RestTemplate
{
"update": {
"name": "xyz",
"id": "C2",
"Description": "aaaaaa",
"members": ["abc", "xyz"]
}
}
Here is my PostMapping Controller
#PostMapping(value = "/update")
public Update update(#RequestBody Update update) {
String url = "";
HttpHeaders headers = createHttpHeaders("username", "passowrd");
JSONObject jsonObject = new JSONObject();
jsonObject.put("update", update);
HttpEntity<JSONObject> request = new HttpEntity<>(jsonObject, headers);
ResponseEntity<Update> update = restTemplate.exchange(url, HttpMethod.POST,request, Update.class);
return update.getBody();
}
And this my POJO
public class Update {
private String name;
private String id;
private String Descripion;
private List<String> members;
}
And Im getting 500
{
"timestamp": "2020-03-13T06:31:21.822+0000",
"status": 500,
"error": "Internal Server Error",
"message": "No HttpMessageConverter for org.json.JSONObject and content type \"application/json\""
}

Try to configure your RestTemplate with a Json Message Converter.
restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());
You may refer this blog post for a detailed explanation
https://www.baeldung.com/spring-httpmessageconverter-rest
And then perform your rest call as below.You will no longer need to explicitly create a Json Object.
String url = "";
HttpEntity<Update> request = new HttpEntity<>(update, headers);
ResponseEntity<Update> firewallGroupUpdate = restTemplate.exchange(url, HttpMethod.POST, request, Update.class);
return firewallGroupUpdate.getBody();

Changed resttemplate.exchange to resttemplate.postForObject.
And also changed the method to return String.
public String groupUpdate(#RequestBody String groupUpdate) {
String url = "";
HttpHeaders headers = createHeaders("username","password");
headers.setContentType(MediaType.APPLICATION_JSON);
restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());
HttpEntity<String> requestEntity = new HttpEntity<String>(groupUpdate, headers);
String response = restTemplate.postForObject(url,requestEntity,String.class);
return response;
}

Related

How to I send a Rest Template Request Body with multiple objects in it

I have to send a request body like this
{
"request": {
"header": {
"correlationId": "Test",
"appId": "12345"
},
"payload": {
"leadId": "12345",
"applicationNo": "",
"proposalNo": "P123",
"policyNo": "100",
"issuanceDt": "01-06-2022",
"docName": "ABCD.pdf",
"docType": "Proposal Form"
}
}
}
I also have headers "username" and "password".
I have created Models for request, header and payload with respective fields.
How do I send this using rest template?
Create a new HttpEntity, populate it with headers and body and exchange, using RestTemplate like this. Payload - is a class containing your payload, and I assumed you have a builder (you can use just a map, indeed)
final HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.add("correlationId", "value");
httpHeaders.add("appId", "value");
HttpEntity<Payload> httpEntity = new HttpEntity<>(Payload.builder()
//bulider population goes here
.build(),httpHeaders);
final RestTemplate restTemplate = new RestTemplate();
restTemplate.exchange(uri, HttpMethod.POST,httpEntity);
For Header, you just need to add parameters in the headers of HTTP request, Payload is what you are looking for, You can define a DTO class having the same JSON structure which will then be automatically deserialized and mapped to your DTO class.
public class Payload{
public String leadId;
public String applicationNo;
public String proposalNo;
public String policyNo;
public String issuanceDt;
public String docName;
public String docType;
}

How to Get particular value from restTemplate in springboot?

I have an api with given request body and response , now I have to call restTemplate for it and get particular response from it
This is my requestBody ->
{"ids":["MS8B50FHS"]}
And this is my response ->
{
"status": 200,
"success": true,
"message": "detail found!",
"data": {
"MS8B50FHS": {
"ids": "MS8B50FHS",
"creditTerm": "Credit 45 days"
}
}
}
Now for this I need to get creditterm by calling a restTemplate
#Override
public String findByUniqueSupplierId (String ids){
final String url = BaseUrl ;
HttpHeaders headers = new HttpHeaders();
HttpEntity<Object> requestEntity = new HttpEntity<>(headers);
Map<String, List<String>> params = new HashMap<>();
params.put("ids", Collections.singletonList(ids));
RestTemplate restTemplate = new RestTemplate();
ResponseEntity<String> object = restTemplate.exchange(url, HttpMethod.POST, requestEntity, String.class , params);
return object.getBody();
}
I was trying something like this but not getting result
You can assign JSON data to objects using the fromJson() method from the Gson library.
String body = object.getBody();
Gson gson = new Gson();
Map<String, Object> map = gson.fromJson(body, HashMap.class);
Map<String, Object> data = (Map<String, Object>) map.get("data");
Map<String, Object> creditTerm = (Map<String, Object>) data.get("MS8B50FHS");
String creditTermValue = creditTerm.get("creditTerm").toString();
System.out.println(creditTermValue);
Could be refactored.

How can I pass headers using RestTemplate?

In my method I initially used RestTemplate postForObject method to post request to an endpoint. Now I have to add default OAuth token and pass it as Post request. Is there any way I can pass both request as well as Default Header as part of POST request by using postForObject?
Initiall I used below postForObject
String result = restTemplate.postForObject(url, request, String.class);
I am looking for something like below
restTemplate.exchange(url,HttpMethod.POST,getEntity(),String.class );
Here is my code
private final String url;
private final MarkBuild header;
public DataImpl(#Qualifier(OAuth) MarkBuild header,RestTemplate restTemplate) {
this.restTemplate= restTemplate;
this.header = header;
}
public void postJson(Set<String> results){
try {
Map<String, String> requestBody = new HashMap<>();
requestBody.put("news", "data");
JSONObject jsonObject = new JSONObject(requestBody);
HttpEntity<String> request = new HttpEntity<String>(jsonObject.toString(), null);
String result = restTemplate.postForObject(url, request, String.class);
}
}
Below is getHttpEntity which I want to pass with Post request
private HttpEntity getHttpEntity(Set <String>results) {
return new HttpEntity<>( null, getHttpHeaders() );
}
private HttpHeaders getHttpHeaders() {
return header.build();
}
}
Is there any way I can pass both request as well as Default Header as
part of POST request by using postForObject?
Yes, there is a way to do that, I can give a basic example:
HttpHeaders lHttpHeaders = new HttpHeaders();
lHttpHeaders.setContentType( MediaType.APPLICATION_JSON );//or whatever it's in your case
String payload="<PAYLOAD HERE>"
try
{
String lResponseJson = mRestTemplate.postForObject( url, new HttpEntity<Object>( payload, lHttpHeaders ), String.class);
return lResponseJson;
}
catch( Exception lExcp )
{
logger.error( lExcp.getMessage(), lExcp );
}
Let me know if this doesn't work!!

Java Springboot Restemplate response 500 while postman is not

I send a post with restTemplate, same params with postman but return 500 while postman is working, thanks for help so much.
Example link:
https://www.baeldung.com/spring-resttemplate-post-json
public void getRestTemplate(String user, String pass) {
RestTemplateBuilder restTemplateBuilder = new RestTemplateBuilder();
MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
converter.setSupportedMediaTypes(Arrays.asList(new MediaType[]{MediaType.ALL}));
converter.setObjectMapper(objectMapper());
return restTemplateBuilder
.messageConverters(converter)
.basicAuthorization(user, pass)
.setConnectTimeout(120000)
.setReadTimeout(120000)
.build();
}
public void abc() {
String user = "...";
String pass = "...";
String url = "...";
RestTemplate restTemplate = getRestTemplate(user, pass);
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
JSONObject jsonObject = new JSONObject();
JSONArray params = new JSONArray();
params.put("a");
params.put("b");
params.put(false);
Map<String, String> map = new HashMap<>();
jsonObject.put("jsonrpc", "2.0");
jsonObject.put("method", "x");
jsonObject.put("params", params);
jsonObject.put("id", 1);
ClientHttpRequestFactory requestFactory = new
HttpComponentsClientHttpRequestFactory(HttpClients.createDefault());
restTemplate.setRequestFactory(requestFactory);
HttpEntity<String> request = new HttpEntity<String>(jsonObject.toString(), headers);
String _response = restTemplate.postForObject(url, request, String.class);
}
/*
json format:
{
"jsonrpc": "2.0",
"method": "x",
"params": [
"a", "b", false
],
"id": 1
}
*/
Postman status 200:
{
"result": null,
"error": null,
"id": 1
}

Spring mapping JSON to java POJO

I have API which returns JSON in this format:
[
{ "shrtName": "abc", "validFrom": "2016-10-23", "name": "aaa", "version": 1 },
{ "shrtName": "def", "validFrom": "2016-11-20", "name": "bbb", "version": 1 },
{ "shrtName": "ghi", "validFrom": "2016-11-22", "name": "ccc", "version": 1 }
]
I have this code which reads API and returns it as a String. But I want to read this API and map it into the Java POJO class.
public String downloadAPI(){
RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
headers.set("API-Key", "4444444-3333-2222-1111-88888888");
HttpEntity<?> requestEntity = new HttpEntity<Object>(headers);
String URL = "https://aaaaaaa.io/api/v1/aaaaaaaaa?date=2015-04-04;
restTemplate.getMessageConverters().add(new StringHttpMessageConverter());
ResponseEntity<String> response = restTemplate.exchange(URL, HttpMethod.GET, requestEntity, String.class);
return response.getBody();
}
My questions:
1) Format of POJO?
2) Changes in my method (return type POJO instead of String)
Your JSON is an array that's why []
Create POJO
public class MyPOJO {
private String shrtName;
private Date validFrom;
private String name;
private int version;
}
Remove message converter and refactor restTemplate exchange method to
ResponseEntity<MyPOJO[].class> response = restTemplate.exchange(URL, HttpMethod.GET, requestEntity, MyPOJO[].class);
This is generic function that I use for GET requests
public <T> T getRequestAndCheckStatus(final String url, final Class<T> returnTypeClass,
final List<MediaType> mediaTypes,
final Map<String, String> headerParams,
final Map<String, Object> queryParams) throws Exception {
final HttpHeaders headers = new HttpHeaders();
headers.setAccept(mediaTypes);
setHeaderParamsIfExists(headers, headerParams);
final HttpEntity<String> requestEntity = new HttpEntity<>(headers);
UriComponentsBuilder uriBuilder = UriComponentsBuilder.fromHttpUrl(url);
setQueryParamsIfExists(uriBuilder, queryParams);
final ResponseEntity<T> entity = restTemplate
.exchange(getUrl(uriBuilder),
HttpMethod.GET,
requestEntity,
returnTypeClass);
Assert.assertEquals(HttpStatus.OK, entity.getStatusCode());
return entity.getBody();
}
private void setHeaderParamsIfExists(HttpHeaders headers, Map<String, String> headerParams) {
if(headerParams != null && !headerParams.isEmpty())
headerParams.entrySet()
.forEach(entry -> headers.set(entry.getKey(), entry.getValue()));
}
private void setQueryParamsIfExists(UriComponentsBuilder uriBuilder, Map<String, Object> queryParams) {
if(queryParams != null && !queryParams.isEmpty())
queryParams.entrySet()
.forEach(entry -> uriBuilder.queryParam(entry.getKey(), entry.getValue()));
}
private URI getUrl(UriComponentsBuilder uriBuilder) {
return uriBuilder.build().encode().toUri();
}
In your case you would call it by
getRequestAndCheckStatus("https://aaaaaaa.io/api/v1/aaaaaaaaa", MyPOJO[].class,
Collections.singletonList(MediaType.APPLICATION_JSON_UTF8),
new HashMap<String, String>(){{ put("API-Key", "4444444-3333-2222-1111-88888888"); }}),
new HashMap<String, Object>(){{ put("Date", "2015-04-04"); }});
Additionaly, for Date I recommend to use long and then in controller parse it to Date. I see that you use https protocol, have you configured certificate ?
Create a pojo with those atrributes and use jackson for convert from json String to your pojo.
public class MapClass {
private String shrtName;
private Date validFrom;
private String name;
private int version;
}

Categories