如何使用javarestTeplate将原始数据添加到主体请求中



如何使用java rest模板将如下示例中的原始数据添加为主体请求

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

我在使用javarest模板发送请求主体中的原始数据时遇到了困难,所以我在这里添加了这段代码以供将来参考(我是java编码的新手(。

下面的代码为我发送消息到MS团队通道工作

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;
}

最新更新