POST JSON object using Spring REST template - json

I am posting JSON object using spring rest template. It works fine for less data, but posting more data throws a Request URI too long error.
final String url = getServiceUrl() + "/rs/doc?param1=test";
RestTemplate restTemp=getRestTemplate();
HttpHeaders headers = new HttpHeaders();
headers.setContentType(org.springframework.http.MediaType.APPLICATION_JSON);
//set your entity to send
HttpEntity<MyBean> request = new HttpEntity<MyBean>(myBean,headers);
List<HttpMessageConverter<?>> messageConverters = new ArrayList<HttpMessageConverter<?>>();
messageConverters.add(new MappingJacksonHttpMessageConverter());
messageConverters.add(new FormHttpMessageConverter());
restTemp.getMessageConverters().addAll(messageConverters);
// send it!
responseEntity = restTemp.exchange(url, HttpMethod.POST, request, String.class);
The request body should accept unlimited data in POST method. But that doesn't seem to work here. Can someone please guide.

Below is working fine for me. I have added security details in the header and the post parameters that I need to sent.
RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
headers.set(ApplicationConstants.API_KEY, ApplicationConstants.TEST_API_KEY_VALUE);
headers.set(ApplicationConstants.AUTH_TOKEN, ApplicationConstants.TEST_API_TOKEN_VALUE);
MultiValueMap<String, String> postParameters = new LinkedMultiValueMap<String, String>();
postParameters.add("purpose", cust.getPaymentPurpose());
postParameters.add("buyer_name", cust.getCustomerName());
postParameters.add("email", cust.getCustomerEmailId());
postParameters.add("phone", cust.getCustomerMobNum());
postParameters.add("send_email", "False");
postParameters.add("send_sms", "False");
HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<MultiValueMap<String, String>>(postParameters, headers);
ResponseEntity<String> result = restTemplate.exchange("YOUR URL", HttpMethod.POST, requestEntity, String.class);
OnlinePaymentModel paymentModel = gson.fromJson(result.getBody(), OnlinePaymentModel.class);

Related

Post JSON Object as response to url

Good day everyone please I am supposed to send back a JSON object as a response from my service using RestTemplate but I am confused about where to add the JSON data with restTemplate.exchange() method.
Please see the code below.
Thank you in advance.
JSONObject json= new JSONObject();
json.put("responseCode", 200);
json.put("responseMessage", "Transaction Successfully proceed");
json.put("responseData", transactionDetail.toJson());
RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<Object> entity = new HttpEntity<>(headers);
restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());
MappingJackson2HttpMessageConverter jsonHttpMessageConverter = new MappingJackson2HttpMessageConverter();
jsonHttpMessageConverter.getObjectMapper().configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
restTemplate.getMessageConverters().add(jsonHttpMessageConverter);
ResponseEntity<String> resultFromVGIL = restTemplate.exchange(bitbackCallBackUrl, HttpMethod.POST, entity, String.class);
I was supposed to add the json object in the HttpEntity
HttpEntity<Object> entity = new HttpEntity<>(json.toString(), headers);

Prettyprinting Spring Boot JSON RESTful response in browser using thymeleaf

I would like to print the json response from a RESTful request in the browser in a easy human readable format, keeping json's linebreaks and indentations.
My current code saves the json response in a String and prints the string without any formatting.
In RESTFulController.java
#Controller
public class RESTFulControllerController {
#RequestMapping("myrequest")
public String myRequest(Model model) {
//--> Initializations
RestTemplate rest_template= new RestTemplate();
String url = "https://example.com/api";
//--> Create http request
HttpHeaders headers = new HttpHeaders();
MultiValueMap<String, String> body_map = new LinkedMultiValueMap<>();
body_map.add("resource_id", "value_of_resource_id");
HttpEntity<MultiValueMap<String, String>> request_entity = new HttpEntity<>(body_map, headers);
//--> Post http request
String response = rest_template.postForObject(url, request_entity, String.class);
//--> Add data for display
model.addAttribute("response", response);
return "print_response";
}
In templates/print_response.html
<body>
[[${response}]]
</body>
There is no need for further processing the response, it will be used only for its visualization in the browser. Is it better to do the formatting in the controller or in the template? and how?
Thanks in advance!
You can try to convert your response string to a json object and then back to a indented string:
ObjectMapper objectMapper = new ObjectMapper();
Object json = objectMapper.readValue(response, Object.class);
String indented = objectMapper.writerWithDefaultPrettyPrinter()
.writeValueAsString(json);

Can pass my own object with RestTemplate PUT

I want to build a small RESTful Service, send a PUT request with an Object of a class I created (MyObject), and getting a response with only status.
My controler:
#RestController
public class MyControler {
#RequestMapping(path = "/blabla/{id}", method = RequestMethod.PUT)
#ResponseBody
public ResponseEntity<String> putMethod (#PathVariable("id") Long id,
#RequestBody MyObject t) {
/*todo*/
return new ResponseEntity<String>(HttpStatus.OK);
}
My Test App
#SpringBootApplication
public class App {
public String httpPut(String urlStr) {
MyObject myObject = new MyObject(p,p,....);
URI url = null;
HttpEntity<MyObject> requestEntity;
RestTemplate rest = new RestTemplate();
rest.getMessageConverters().add(new MappingJackson2HttpMessageConverter());
HttpHeaders headers = new HttpHeaders();
List<MediaType> list = new ArrayList<MediaType>();
list.add(MediaType.APPLICATION_JSON);
headers.setAccept(list);
headers.setContentType(MediaType.APPLICATION_JSON);
headers.add("Content-Type", "application/json");
requestEntity = new HttpEntity<Transaction>(t, headers);
ResponseEntity<String> response =
rest.exchange(url, HttpMethod.PUT, requestEntity, MyObject.class);
return response.getStatusCode().getValue();
}
Im getting an HttpClientErrorException: 400 Bad Request
Where is my mistake? What I want is for Spring to automaticly serialize the MyObject. MyObject class is implementing serializable.
What do I miss?
}
Maybe you're doing to much?
Did you try to put the object as json via postman or something similar? If so what is the response?
Nevertheless i created a minimal example for consuming a service via Springs RestTemplate.
This is all needed code for getting a custom object AND putting a custom object via RestTemplate
public void doTransfer(){
String url = "http://localhost:8090/greetings";
RestTemplate restTemplate = new RestTemplate();
ResponseEntity<Greeting> greeting = restTemplate.getForEntity(url, Greeting.class);
LOGGER.info(greeting.getBody().getValue());
Greeting myGreeting = new Greeting();
myGreeting.setValue("Hey ho!");
HttpEntity<Greeting> entity = new HttpEntity<Greeting>(myGreeting);
restTemplate.exchange(url, HttpMethod.PUT, entity, Greeting.class);
}
I've provided a sample project with a sender (maybe not a good name .. it is the project with the greetings endpoint) and a receiver (the project which consumes the greetings endpoint) on Github
Try to do this:
ResponseEntity<MyObject> responseSerialized =
rest.exchange(url, HttpMethod.PUT, requestEntity, MyObject.class);

How to send JSON data in request to rest web service

I have created a rest webservice which has a below code in one method:
#POST
#Path("/validUser")
#Consumes(MediaType.APPLICATION_JSON)
#Produces(MediaType.APPLICATION_JSON)
public JSONObject validUserLogin(#QueryParam(value="userDetails") String userDetails){
JSONObject json = null;
try{
System.out.println("Service running from validUserLogin :"+userDetails);
json = new JSONObject(userDetails);
System.err.println("UserName : "+json.getString("userName")+" password : "+json.getString("password"));
json.put("httpStatus","OK");
return json;
}
catch(JSONException jsonException) {
return json;
}
}
I am using Apache API in the client code.And below client code is calling this service, by posting some user related data to this service:
public static String getUserAvailability(String userName){
JSONObject json=new JSONObject();
try{
HttpContext context = new BasicHttpContext();
HttpClient client = new DefaultHttpClient();
client.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.RFC_2109);
URI uri=new URIBuilder(BASE_URI+PATH_VALID_USER).build();
HttpPost request = new HttpPost(uri);
request.setHeader("Content-Type", "application/json");
json.put("userName", userName);
StringEntity stringEntity = new StringEntity(json.toString());
request.setEntity(stringEntity);
HttpResponse response = client.execute(request,context);
System.err.println("content type : \n"+EntityUtils.toString(response.getEntity()));
}catch(Exception exception){
System.err.println("Client Exception: \n"+exception.getStackTrace());
}
return "OK";
}
The problem is, I am able to call the service, but the parameter I passed in the request to service results in null.
Am I posting the data in a wrong way in the request. Also I want to return some JSON data in the response, but I am not able to get this.
With the help of Zack , some how i was able to resolve the problem,
I used jackson-core jar and changed the service code as below.
#POST
#Path("/validUser")
#Consumes(MediaType.APPLICATION_JSON)
#Produces(MediaType.APPLICATION_JSON)
public JSONObject validUserLogin(String userDetails){
ObjectMapper mapper = new ObjectMapper();
JsonNode node = mapper.readValue(userDetails, JsonNode.class);
System.out.println("Service running from validUserLogin :"+userDetails);
System.out.println(node.get("userName").getTextValue());
//node.("httpStatus","OK");
return Response.ok(true).build();
}

Possible to pass raw JSON to a Rest API using the Spring RestTemplate?

Is it possible to pass raw JSON to a Rest API using the Spring RestTemplate?
I am attempting the following:
List<HttpMessageConverter<?>> httpMessageConverters = new ArrayList<HttpMessageConverter<?>>();
httpMessageConverters.add(new MappingJacksonHttpMessageConverter());
restTemplate.setMessageConverters(httpMessageConverters);
String jsonText = // raw JSON
httpHeaders.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<?> entity = new HttpEntity<Object>(jsonText, httpHeaders);
restTemplate.exchange(url, HttpMethod.POST, entity, responseClass);
When I invoke this request, I get a HTTP 400 error response, meaning bad request. However, all headers and the JSON body are identical as that submitted using a HTTP client I have.
In contrast, the following works fine when I create the MyRequest object and set it on the HttpEntity:
List<HttpMessageConverter<?>> httpMessageConverters = new ArrayList<HttpMessageConverter<?>>();
httpMessageConverters.add(new MappingJacksonHttpMessageConverter());
restTemplate.setMessageConverters(httpMessageConverters);
MyRequest myRequest = new MyRequest();
httpHeaders.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<?> entity = new HttpEntity<Object>(myRequest, httpHeaders);
restTemplate.exchange(url, HttpMethod.POST, entity, responseClass);
Therefore, I am wondering how I can invoke my REST API using raw JSON in String format?
This is Method
String url = String.format("https://SITE");
RestTemplate template = new RestTemplate();
template.getMessageConverters().add(new StringHttpMessageConverter());
String valor ="{\"cmd\":\"123\", \"includeImei\":\"true\"}";
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
headers.set("Authenticate", "TOKEN");
HttpEntity<String> entity = new HttpEntity<String>(valor, headers);
URI valoresdevueltos = template.postForLocation(url, entity);