簡體   English   中英

Mail 365 Rest API從Java錯誤發送消息

[英]Mail 365 rest api send message from java error

我正在嘗試使用java httpClient v4.4發送消息,我以您提供的消息為例。 這里

我經常收到此錯誤:{“錯誤”:{“代碼”:“ ErrorInvalidRequest”,“消息”:“無法讀取請求正文。”}}

這是我的代碼。

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

我究竟做錯了什么?? 有人可以建議嗎?

網址為https://outlook.office365.com/api/v1.0/me/sendmail是正確的。 標頭和Http方法也。

但是有效負載的格式錯誤(元素的嵌套出現問題)-這就是為什么服務響應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表示形式。 看看GSONJackson

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM