如何解决 java 中的响应代码 406 错误?

How to resolve respond code 406 erro in java?

我可以使用 Microsoft Outlook 拨打休息电话 api。这是我写的代码。

public static void sendGet() {

    String url = "https://outlook.office365.com/api/v1.0/me/folders/Inbox/messages";
    final String CONTENT_TYPE = "application/json";
    final String ACCEPT_LANGUAGE = "en-US,en;q=0.8";

    try {

        URL obj = new URL(url);
        HttpsURLConnection connection = (HttpsURLConnection) obj.openConnection();

        connection.setRequestMethod("GET");
        connection.setDoInput(true);
        connection.setUseCaches(false);
        connection.setRequestProperty("Content-Type", CONTENT_TYPE);
        connection.setRequestProperty("Accept-Language", ACCEPT_LANGUAGE);
        connection.setRequestProperty("Authorization", "Basic c2h1YW5nQHZpdfdGVjaGluYydf5jb2fdXjhNCE="); //base64 encoding of auth username:password

        int responseCode = connection.getResponseCode();
        System.out.println("response code: " + responseCode);

        BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));

        String inputLine;
        StringBuffer response = new StringBuffer();

        while((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }

        in.close();

        System.out.println(response.toString());

    } catch (MalformedURLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

我正在尝试 return 包含我收件箱中所有消息的 json 响应,但它 return 出现错误代码为 406 的 IO 异常。

我很确定 content-type "application/json" 是受支持的,当我使用 post man 执行其余调用时,它将能够成功 return 我 json数据。

来自 postman header,支持 application/json 的 content-type。有人知道我做错了什么吗?

The requested resource is only capable of generating content not acceptable according to the Accept headers sent in the request.

Source

换句话说,将 API 返回的内容类型添加到您的接受 header。

您是否尝试过将 Accept: application/json 添加到 HTTP header。

Accept header 被 HTTP 客户端用来告诉服务器他们接受什么内容类型。然后服务器发回一个响应,其中包括 Content-Type header 告诉客户端返回内容的内容类型实际上是什么。

tldr; Accept 是客户端能够消费的内容,Content-Type 是数据的实际内容。