Mail 365 rest api 发送邮件 java 错误

Mail 365 rest api send message from java error

我正在尝试使用 java httpClient v4.4 发送消息 我以您提供的消息为例。here

我经常收到这个错误: {"error":{"code":"ErrorInvalidRequest","message":"Cannot read the request body."}}

这是我的代码。

String message = "{\"Message\":{\"Subject\":\"Meet for lunch?\",\"Body\":{\"ContentType\":\"Text\",\"Content\":\"The new cafeteria is open.\"},\"ToRecipients\":[{\"EmailAddress\":{\"Address\":\"my@mailadress.com\"}}],\"SaveToSentItems\":\"true\"}}";
CloseableHttpClient httpclient = HttpClients.createDefault();
    HttpPost post = new HttpPost("https://outlook.office365.com/api/v1.0/me/sendmail");
    post.setHeader("authorization" ,"Bearer "+accessToken);
    post.setHeader("Accept", "application/json");
    post.setHeader("contnet-type", "application/json");
    post.setEntity(stringEntity);

    CloseableHttpResponse response = httpclient.execute(post);
    InputStream  in=null;
    BufferedReader buffer=null;


        String microsoftResponse = "";
        //System.out.println(response.toString());
        in= response.getEntity().getContent();
buffer = new BufferedReader(new InputStreamReader(in));
          String s = "";
          while ((s = buffer.readLine()) != null) {
            microsoftResponse += s;
          }
          System.out.println(microsoftResponse);
    }
    catch(Exception e)
    {
        e.printStackTrace();
    }

我做错了什么??有人可以提出建议吗??

URL 是 https://outlook.office365.com/api/v1.0/me/sendmail 是正确的。 Headers 和 Http Method 也一样。

但负载格式错误(元素嵌套出现问题)- 这就是服务响应 Cannot read the request body..

的原因

正确的消息负载应该是

{
    "Message": {
        "Body": {
            "Content": "The new cafeteria is open.",
            "ContentType": "Text"
        },
        "Subject": "Meet for lunch?",
        "ToRecipients": [
            {
                "EmailAddress": {
                    "Address": "my@mailadress.com"
                }
            }
        ]
    },
    "SaveToSentItems": "true"
}

或准备在您的 Java 代码中使用(正确转义):

String message = "{\n" +
            "\"Message\": {\n" +
            "        \"Body\": {\n" +
            "            \"Content\": \"The new cafeteria is open.\",\n" +
            "            \"ContentType\": \"Text\"\n" +
            "        },\n" +
            "        \"Subject\": \"Meet for lunch?\",\n" +
            "        \"ToRecipients\": [\n" +
            "            {\n" +
            "                \"EmailAddress\": {\n" +
            "                    \"Address\": \"my@mailadress.com\"\n" +
            "                }\n" +
            "            }\n" +
            "        ]\n" +
            "    },\n" +
            "    \"SaveToSentItems\": \"true\"\n" +
            "}";

我强烈建议您使用一个库将 POJO 转换成它的 JSON 表示。看看GSON or Jackson