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);
Related
I came across a weird scenario.
I was calling a External API which is returning Lists of LinkedHashMap (E.g: List<LinkedHashMap<String, String>)
So the question is how to convert this JSON response to Custom Response object in Java
Use the below code to convert JSON response to Custom Response object in Java.
ResponseEntity<Object> response = restTemplate.exchange(
pathURL,
HttpMethod.{GET/POST ..},
createHeader(),
Object.class
);
final List<LinkedHashMap> responseList = objectMapper
.convertValue(
response.getBody(),
new TypeReference<List<LinkedHashMap>>() {
}
);
LinkedHashMap<String, String> responseMap = responseList.get(0);
CustomResponseObj infoResp = objectMapper.convertValue(responseMap, CustomResponseObj.class);
private HttpEntity<?> createHeader() {
HttpHeaders headers = new HttpHeaders();
return new HttpEntity<>(headers);
}
In JsnoToApex class I try to GET JSON file from https://openweathermap.org/current. When I try to parse JSON.CreateParses I get these error: Illegal assignment from System.JSONParser to JsonParser
I try to make API that show weather in London.
public with sharing class JsonToApex {
#future(callout=true)
public static void parseJSONResponse() {
String resp;
Http httpProtocol = new Http();
// Create HTTP request to send.
HttpRequest request = new HttpRequest();
// Set the endpoint URL.
String endpoint = 'https://samples.openweathermap.org/data/2.5/weather?q=London,uk&appid=b6907d289e10d714a6e88b30761fae22';
request.setEndPoint(endpoint);
// Set the HTTP verb to GET.
request.setMethod('GET');
// Send the HTTP request and get the response.
// The response is in JSON format.
HttpResponse response = httpProtocol.send(request);
resp = response.getBody();
JSONParser parser = JSON.createParser(resp);
JsonMapper response = (JsonMapper) System.JSON.deserialize(res.getBody(), JsonMapper.class);
}
}
I expect to get Json file and in future map it using https://json2apex.herokuapp.com/
The problem was in first JSONParser. I had to add System.JSONParser to make it work.
System.JSONParser parser = JSON.createParser(resp);
You may have two approaches:
If you have already map the JSON into an Apex class, you may just use
JSON2Apex aClass = (JSON2Apex) System.JSON.deserialize(resp, JSON2Apex.class);
Where JSON2Apex is the mapping Apex class.
Use the JSON.deserializeUntyped(String jsonString) to deserialize the JSON to any Object in Apex class, like:
Map<String, Object> objMap = (Map<String, Object>) JSON.deserializeUntyped(resp);
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);
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);
Hello In frist time I want apologize if my english isn't so good
I want send Multipart request to the server by Apache HttpClient. This request consist from several types of parts. One of these part is JSON. JSON is created by Jackson.
HttpClient httpclient = new DefaultHttpClient();
httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
HttpPost httppost = new HttpPost("http://xxx.xxx.xxx.xx:8080/synchronize");
HttpResponse response =null;
CProject project = new CProject();
project.setId(10L);
project.setName("name");
ObjectMapper mapper = new ObjectMapper();
String json = mapper.writeValueAsString(project);
MultipartEntity multipart = new MultipartEntity( HttpMultipartMode.BROWSER_COMPATIBLE);
multipart.addPart("project", new StringBody(json,"application/json",Charset.forName("UTF-8")) );
httppost.setEntity(multipart);
response = httpclient.execute(httppost);
Structure of CProject is very simple
public class CProject implements Serializable{
private Integer id;
private String name;
}
And I wand catch this request on server as parameter with anotations #RequestParam or #ModelAttribute but no with #RequestBody because this catch full request - and I need send multiply parameters(Multipart Entity).
Code on server
#RequestMapping (value = "/synchronize", method = RequestMethod.POST)
public #ResponseBody
List<Object> getRequest (#RequestParam CProject project, HttpServletResponse response)
{
return null;
}
Problem is that variable project is created but its atributes are null.
I try several tutorials on net what works with #RequestBody and send request on server and set full header as "application/json". And my application works if I change header of full request as JSON and send them on server, and catch this as #RequestBody on server this work. But I need send json as parameter.
Thanks for any ideas.