Mail 365 rest api从java错误发送消息

时间:2015-03-19 14:50:59

标签: java rest office365

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

我不断收到此错误: {“error”:{“code”:“ErrorInvalidRequest”,“message”:“无法读取请求正文。”}}

这是我的代码。

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

我做错了什么?任何人都可以提出建议吗?

1 个答案:

答案 0 :(得分:0)

网址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