Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to do post request with raw data via spring rest template

Can some one tell me how to send a POST request with raw data parameters as in the picture below enter image description here

i have tried the following code but its not working

HttpHeaders headers = new HttpHeaders();
                headers.setContentType(MediaType.APPLICATION_JSON);
            JsonObject properties = new JsonObject();
            MultiValueMap<String, String> params = new LinkedMultiValueMap<>();         
            try {

                properties.addProperty("app_id", appId);
                properties.addProperty("identity","TestAPI");
                properties.addProperty("event", "TestCompleted");
                properties.addProperty("testType", t.getTestType());
                properties.addProperty("testName",t.getTestName());
                properties.addProperty("chapter","");
                properties.addProperty("module","");
                properties.addProperty("pattern",t.getTestPattern());
                HttpEntity<String> request = new HttpEntity<>(
                        properties.toString(), headers);
               // params.add("properties", properties.toString());
                 restTemplate.postForObject(url, request, String.class);

can someone help?

like image 731
Bhargav Avatar asked Sep 16 '25 11:09

Bhargav


1 Answers

Try this :

@RestController
public class SampleController { 
    @RequestMapping("/req")
    public String performReqest(){
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);        
        JsonObject properties = new JsonObject();
        properties.addProperty("no", "123");
        properties.addProperty("name", "stackoverflow");
        HttpEntity<String> request = new HttpEntity<>(properties.toString(), headers);
        RestTemplate restTemplate = new RestTemplate();
        String response = restTemplate.postForObject("http://localhost:4040/student", request, String.class);
        return "Response from Server is : "+response;       
    }

    @RequestMapping("/student")
    public String consumeStudent(@RequestBody Student student){
        System.out.println(student);
        return "Hello.."+student.name;
    }   
}

class Student{
    public int no;
    public String name; 
    public Map<String,String> properties;   
}

Don't forgot to move Student class and change all field to private with require getters and setters. Above code is only for demo purpose.

like image 189
mcacorner Avatar answered Sep 18 '25 09:09

mcacorner