简体   繁体   中英

how to add raw data to body request using java restTeplate

How to add raw data like below sample as body request using java rest-template

{
  "body": {
    "content": "This is sent via postman to MS-team general channel"
  }
}

i was having difficulty in sending raw data in request body using java rest-template, so i'm adding this code here for future reference(i'm a newbie to java coding).

Below code worked for me for sending a message to MS-Team channel

    public JSONObject sendMessage(String team_ID, String channel_ID){
        JSONObject res =null;        
        RestTemplate restTemplate = new RestTemplate();
        String url="https://graph.microsoft.com/beta/teams/"+team_ID+"/channels/"+channel_ID+"/messages";
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);                
        String token = "xxxxxxxxxx";
        headers.set("Authorization","Bearer "+token);
        


         // This  didn't worked 
        /*MultiValueMap<String, Object> map = new LinkedMultiValueMap<String, Object>();
        map.add("content", "Welcome to General channel message sent via intellij IDE");

        MultiValueMap<String, String> map1= new LinkedMultiValueMap<String, String>();
        map1.add("content", "Welcome to General channel message sent via intellij IDE");
        //map.add("body", "Welcome to General channel message sent via intellij IDE");*/
        
         // This one also didn't worked 
        //JSONObject jsonObject = new JSONObject();
        //jsonObject.put("body", "{ \"body\": {\"content\":\"Welcome to General channel message sent via intellij IDE  using java coding & http rest-Template\"}}");

        // This one also didn't worked 
        //JSONObject jsonObject = new JSONObject();
        //jsonObject.put("body", "{\"content\":\"Welcome to General channel message sent via intellij IDE  using java coding & http rest-Template\"}");
        
        // This one worked
        String requestJson = "{ \"body\": {\"content\":\"Welcome to General channel message sent via intellij IDE using java coding & http rest-Template\"}}";
        
                 
        // HttpEntity<String> request = new HttpEntity<String>(jsonObject.toString(),headers);
        HttpEntity<String> request = new HttpEntity<String>(requestJson,headers);
        ResponseEntity<String> response=null;
        try {
            response = restTemplate.postForEntity(url, request, String.class);
            res= new JSONObject(response.getBody());
            System.out.println(res);
        }catch(Exception e){
            e.printStackTrace();
        }
        return  res;
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM