1

Im trying to send message to MS Team through JAVA . MS Team exposes the POST API through MS Graph which we can use to send messages to Teams channel using teams ID and channel ID . This what I understood from doc : https://learn.microsoft.com/en-us/graph/sdks/sdk-installation#install-the-microsoft-graph-java-sdk

There are two codes which I have written . none of them are working

CODE 1

public static void main(String[] args) {
                
            RestTemplate restTemplate = new RestTemplate();
            String url = "https://graph.microsoft.com/v1.0/teams/<team id>/channels/<channel id>/messages";     
            HttpHeaders headers = new HttpHeaders();
            String requestJson = "{\"queriedQuestion\":\"Is there pain in your hand?\"}";
            headers.setContentType(MediaType.APPLICATION_JSON);
            headers.setBearerAuth("token");  
                
            HttpEntity<String> entity = new HttpEntity<String>(requestJson, headers);
            String answer = restTemplate.postForObject(url, entity, String.class);
            System.out.println(answer);

    }

error coming is :

Exception in thread "main" org.springframework.web.client.HttpClientErrorException$BadRequest: 400 Bad Request: "{"error":{"code":"BadRequest","message":"Missing body content","innerError":{"date":"2023-06-22T07:44:37","request-id":"dc287932-45c4-4940-8f23-c717cb5d6e09","client-request-id":"dc287932-45c4-4940-8f23-c717cb5d6e09"}}}" at org.springframework.web.client.HttpClientErrorException.create(HttpClientErrorException.java:103) at org.springframework.web.client.DefaultResponseErrorHandler.handleError(DefaultResponseErrorHandler.java:183) at org.springframework.web.client.DefaultResponseErrorHandler.handleError(DefaultResponseErrorHandler.java:137) at org.springframework.web.client.ResponseErrorHandler.handleError(ResponseErrorHandler.java:63) at org.springframework.web.client.RestTemplate.handleResponse(RestTemplate.java:915) at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:864) at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:764) at org.springframework.web.client.RestTemplate.postForObject(RestTemplate.java:481) at oe.kubeapi.cloudcontroller.TeamMes4.main(TeamMes4.java:36)

CODE 2

public static void main(String[] args) {
        
        RestTemplate restTemplate = new RestTemplate();
        
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        HttpEntity<String> entity = new HttpEntity<>("Hello World 3", headers);
    
        headers.setBearerAuth("token");
        headers.add("Header", "header1");
        
        UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl("https://graph.microsoft.com/v1.0/teams/<team id>/channels/<channel id>/messages");
        
        HttpEntity<String> response = restTemplate.exchange(
                builder.toUriString(), 
                HttpMethod.POST,
                entity, 
                String.class);
    }

error coming is :

Exception in thread "main" org.springframework.web.client.HttpClientErrorException$BadRequest: 400 Bad Request: "{"error":{"code":"BadRequest","message":"Unable to read JSON request payload. Please ensure Content-Type header is set and payload is of valid JSON format.","innerError":{"date":"2023-06-22T07:52:21","request-id":"229cc590-dcdf-47ed-89cf-e47ddf136be7","client-request-id":"229cc590-dcdf-47ed-89cf-e47ddf136be7"}}}" at org.springframework.web.client.HttpClientErrorException.create(HttpClientErrorException.java:103) at org.springframework.web.client.DefaultResponseErrorHandler.handleError(DefaultResponseErrorHandler.java:183) at org.springframework.web.client.DefaultResponseErrorHandler.handleError(DefaultResponseErrorHandler.java:137) at org.springframework.web.client.ResponseErrorHandler.handleError(ResponseErrorHandler.java:63) at org.springframework.web.client.RestTemplate.handleResponse(RestTemplate.java:915) at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:864) at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:764) at org.springframework.web.client.RestTemplate.exchange(RestTemplate.java:646) at oe.kubeapi.cloudcontroller.TeamMessage1.main(TeamMessage1.java:33)

I truly don't understand what is the issue. I searched lot and modified the code accordingly . I referred this question also : POST request via RestTemplate in JSON

please suggest

user2315104
  • 2,378
  • 7
  • 35
  • 54

1 Answers1

0

This is the documentation page of the endpoint you invoke.

The error message of your first try is

Missing body content

The complaint claims that you did not properly define the body content, which is good news in the sense that you were able to request the endpoint you wanted after all and you are pretty close to make it work.

enter image description here

So, you need to represent a chatMessage object in JSON format. Something like this:

{
  "attachments": [{"@odata.type": "microsoft.graph.chatMessageAttachment"}],
  "body": {"@odata.type": "microsoft.graph.itemBody"},
  "channelIdentity": {"@odata.type": "microsoft.graph.channelIdentity"},
  "chatId": "String",
  "createdDateTime": "String (timestamp)",
  "deletedDateTime": "String (timestamp)",
  "etag": "String",
  "eventDetail": {"@odata.type": "microsoft.graph.eventMessageDetail"},
  "from": {"@odata.type": "microsoft.graph.chatMessageFromIdentitySet"},
  "id": "String (identifier)",
  "importance": "String",
  "lastEditedDateTime": "String (timestamp)",
  "lastModifiedDateTime": "String (timestamp)",
  "locale": "String",
  "mentions": [{"@odata.type": "microsoft.graph.chatMessageMention"}],
  "messageHistory": [{"@odata.type": "microsoft.graph.chatMessageHistoryItem"}],
  "messageType": "String",
  "policyViolation": {"@odata.type": "microsoft.graph.chatMessagePolicyViolation"},
  "reactions": [{"@odata.type": "microsoft.graph.chatMessageReaction"}],
  "replyToId": "String (identifier)",
  "subject": "String",
  "summary": "String",
  "webUrl": "String"
}

Example taken from the documentation:

GraphServiceClient graphClient = GraphServiceClient.builder().authenticationProvider( authProvider ).buildClient();

ChatMessage chatMessage = new ChatMessage();
ItemBody body = new ItemBody();
body.content = "Hello World";
chatMessage.body = body;

graphClient.teams("fbe2bf47-16c8-47cf-b4a5-4b9b187c508b").channels("19:4a95f7d8db4c4e7fae857bcebe0623e6@thread.tacv2").messages()
    .buildRequest()
    .post(chatMessage);

Notice that a ChatMessage object is being created and an ItemBody is being assigned to its body member. Also notice the use of GraphServiceClient.

Lajos Arpad
  • 64,414
  • 37
  • 100
  • 175
  • Thanks . I have seen this doc already , but the issue is , they dont have any example of passing the bearer token to graphClient . I have the bearer token generated from Auth code provider – user2315104 Jun 22 '23 at 09:41
  • @user2315104 is this page helpful? https://github.com/microsoftgraph/msgraph-sdk-java/issues/961 – Lajos Arpad Jun 22 '23 at 10:25