Sending raw JSON using Postman value is null - java

A pleasant day.
I am having trouble with simply displaying string in raw JSON format using Postman.
This is what I have in my Java code:
#RestController
public class HeroController {
#RequestMapping(method = {RequestMethod.POST}, value = "/displayHero")
#ResponseBody
public Map<String, String> displayInfo(String name){
//System.out.println(name);
Map<String, String> imap = new LinkedHashMap<String, String>();
map.put("hero", name);
return imap;
}
}
Every time I test this in Postman, I always get null (again if I am using raw format):
{
"hero": null
}
But using form-data, on the other hand, displays just what I entered.
{
"hero": "wolverine"
}
Any information, or should do in Postman to make this raw format works instead of form-data? By the way, the raw format value is JSON(application/json), and in the Header Tab, the value of Content-Type is application/json; charset=UTF-8.
Thank you and have a nice day ahead.

Try the following code for consuming the request body as JSON, in spring boot:-
#RequestMapping(value = "/displayHero", method = POST, consumes = APPLICATION_JSON_VALUE, produces = APPLICATION_JSON_VALUE)
#ResponseBody
public String displayInfo(HttpEntity<String> httpEntity) {
String json = httpEntity.getBody();
// json contains the plain json string
// now you can process the json object information as per your need
// and return output as per requirements.
return json;
}
This code will accept json body of POST Request and then return it as response.

Related

Get values from received html body

I want to get the body values from received html request body using Spring boot:
#PostMapping(value = "/v1/notification")
public ResponseEntity<String> handleNotifications(
#RequestParam(value = "uniqueid", required = false)) String uniqueidValue,
#RequestParam(value = "type", required = false)) String statusValue) {
// Get values from html body
return new ResponseEntity<>(HttpStatus.OK);
}
For example when I receive into the notification body:
some_key=some_value&sec_key=sec_value
I would like to parse the values. How I can implement this?
You can take the key value pair request with using Map and #RequestBody as below:
#PostMapping(value = "/v1/notification")
public ResponseEntity handleNotifications(#RequestBody Map<String,String> keyValuePairs) {
// here you can use keyValuePairs
// you can process some specific key like
String value = keyValuePairs.get("someSpecificKey");
return ResponseEntity.ok(value);
}
Here I attach example postman request :

Can I get a ResponseEntity (Spring) parametrized with a type either parametrized?

I'm using RestTemplate and SpringBoot 2.0.
I have this class which represents a custom JSON response to rest calls.
MyCustomResponse<T> {
private T content;
public T getContent() {
return content;
}
}
The code snippet below is a example of use:
String LOCALHOST = "http://localhost:8900";
final HttpHeaders headers = new HttpHeaders();
headers.add(HttpHeaders.ACCEPT, "application/json");
String url = String.format("%s/ticket/%s", LOCALHOST, protocol);
final HttpEntity<Ticket> request = new HttpEntity<>(headers);
This works fine:
ResponseEntity<MyCustomResponse> response =
testRestTemplate.getForEntity(url, RespostaPadrao.class);
But it's not what I need, because getContent returns a object that looks like:
Map< Map < String, Map < String, Map < String, Map < String, Integer >>>>>
and because I want to test a Ticket object instead.
In this line, can I use reflection to parametrize the response or this is impossible?
ResponseEntity<MyCustomResponse> response =
testRestTemplate.getForEntity(url, MyCustomResponse.class);
I know how to fix it with ResponseEntity<String> and parse the JSON to my Ticket. But what I really need is know if is possible delegate this task to RestTemplate or not.
Thanks!

How to manipulate a payload in a REST API?

This is my first webservice and I am still understanding POST's GET's etc. I have been working on a Spring REST service. What I am confused about is how do I deal with a payload sent by another application?
Basically I have one app sending a json payload to my Spring REST API and I want to be able to grab the values of each key and store them in an object
Here is basically my code so far:
#RestController
public class Controller {
Payload payload;
Item item;
// gets the payload
#RequestMapping(value = "/buildevents/get-job", method = RequestMethod.GET, headers = "Accept=application/json")
public ResponseEntity <Payload> get() {
payload = new Payload();
payload.setJobName("Testing");
payload.setProjectName("Testing2");
payload.setUserName("Me");
payload.setPassWord("pass");
return new ResponseEntity<Payload>(payload, HttpStatus.OK);
}
#RequestMapping(value = "buildevents/create-item", method = RequestMethod.POST, headers = "Accept=application/json")
public ResponseEntity <Item> createItem(#RequestBody Item item) {
item.setProject(" ");
item.setItemName(payload.getJobName());
item.setUserName(" ");
item.setPassWord(" ");
return new ResponseEntity<Item>(item, HttpStatus.OK);
}
}
I want to do GET'S and POST'S from this code. The info I need to do so will come from a json payload POST to this service though, so I need to store the info from it in my object's setters. I don't know if I'm going about this wrong, but I'm lost.

How to return a string as valid JSON from Spring web app?

I have a Spring endpoint for my REST web services app that I want to return a string:
"Unauthorized: token is invalid"
But my javascript on the front-end chokes on this:
JSON.parse("Unauthorized: token is invalid") //Unexpected token U
How do I get my app to return a valid JSON string? Here is my current code:
#RequestMapping(value="/401")
public ResponseEntity<String> unauthorized() {
return new ResponseEntity<String>("Unauthorized: token is invalid", HttpStatus.UNAUTHORIZED);
}
Return a Map instead.
Map<String,String> result = new HashMap<String,String>();
result.put("message", "Unauthorized...");
return result;
You don't need to return a ResponseEntity, you can directly return a POJO or collection. Add #ResponseBody to your handler method if you want to return a POJO or collection.
Also, I'd say it's better to use forward over redirect for errors.
#Neil presents a better alternative to what you are trying to accomplish.
In response to the question asked however, you are close.
The modified code below should produce a valid JSON response
#RequestMapping(value="/401")
public ResponseEntity<String> unauthorized() {
String json = "[\"Unauthorized\": \"token is invalid\"]";
HttpHeaders responseHeaders = new HttpHeaders();
responseHeaders.setContentType(MediaType.APPLICATION_JSON);
return new ResponseEntity<String>(json, responseHeaders, HttpStatus.UNAUTHORIZED);
}

In Spring, Is there a way to return different Content-Type values for the header?

I would like to set the produces = text/plain to produces = application/json when I encounter an error.
#RequestMapping(value = "/v0.1/content/body", method = RequestMethod.GET, produces = "text/plain")
#ResponseBody
public Object getBody(#RequestParam(value = "pageid") final List<String> pageid, #RequestParam(value = "test") final String test) {
if (!UUIDUtil.isValid(pageid)) {
Map map = new HashMap();
map.put("reason", "bad pageId");
map.put("pageId", pageId);
map.put("test", test);
return new ResponseEntity<Object>(map, HttpStatus.BAD_REQUEST);
}
return "hello";
}
The problem with this code is that it doesn't print the error as json when I send an invalid pageId. It gives me a HTTP 406 error Not acceptable, because it expects to produce text/plain but I didn't return a String.
The cleanest way to handle errors is to use #ExceptionHandler:
#ExceptionHandler(EntityNotFoundException.class) //Made up that exception
#ResponseBody
#ResponseStatus(value = HttpStatus.NOT_FOUND)
public ErrorObject handleException(Exception e) {
return new ErrorObject(e.getMessage());
}
Then assuming you've configured your resolvers properly and put the right JSON serialization library in the classpath, the instance of ErrorObject will be returned to the client as a JSON response.
Of course you can set up multiple #ExceptionHandler methods as needed.

Categories