waleed
waleed

Reputation: 91

Spring boot: Sending a JSON to a post request that uses a model as a param

Lets say I have a predefined post mapping as such:

 @PostMapping(value = "/add", produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<String> addVal(@RequestBody final valDetail newVal) {
        //Do Stuff
    }

and the valDetail object as follows:

@Data
@Component
@Entity
@Table(name = "val_portal")
public class valDetail {
    @Id
    @Column(name = "valcode")
    private String valCode;
    @Column(name = "valname")
    private String valName;
   }

How would I go about actually sending JSON values from a separate service to this /add endpoint so that they are properly received as a valDetail object? Currently I tried this implementation but I keep getting a 415 response code.

JSONObject valDetail = new JSONObject();
valDetail.put("valCode",request.getAppCode().toLowerCase());
valDetail.put("valName", request.getProjectName());

 String accessToken = this.jwtUtility.retrieveToken().get("access_token").toString();
HttpHeaders authHeaders = new HttpHeaders();
authHeaders.setBearerAuth(accessToken);
authHeaders.setContentType(MediaType.APPLICATION_JSON);

HttpEntity<String> entity = new HttpEntity<String>(valDetail.toString(), authHeaders);

ResponseEntity<String> loginResponse = restTemplate.exchange(uri,
                        HttpMethod.POST,
                        entity,
                        String.class);




Upvotes: 0

Views: 213

Answers (1)

Faheem azaz Bhanej
Faheem azaz Bhanej

Reputation: 2396

If you want to pass data as json you don't want to take Model try to use @ResponseBody annotation to transfer data through json.

@PostMapping(value = "/add", produces = MediaType.APPLICATION_JSON_VALUE)
@ResponseBody
public ResponseEntity<String> addVal(@RequestBody final valDetail newVal) {
    //Do Stuff
}

Upvotes: 1

Related Questions