当我使用 Microsoft Graph 的访问令牌时,访问失败并响应 400 错误

Smd*_*Smd 1 java microsoft-graph-api

我尝试在 Java 上使用 Microsoft Graph。我成功获得了访问令牌。

但是,当我通过 HttpURLConnection 使用此令牌时,我的访问被拒绝并从 Microsoft 服务器捕获了 400 错误。

    HttpURLConnection con = null;
    String url_str = "https://graph.microsoft.com/v1.0/me";
    String bearer_token = "EwA4A8l6BA...";

    URL url = new URL(url_str);
    con = ( HttpURLConnection )url.openConnection();
    con.setDoInput(true);
    con.setDoOutput(true);
    con.setUseCaches(false);
    con.setRequestMethod("GET");
    con.setRequestProperty("Authorization","Bearer " + bearer_token);
    con.setRequestProperty("Host","graph.microsoft.com");
    con.connect();

    BufferedReader br = new BufferedReader(new InputStreamReader( con.getInputStream() )); // Error has been occured here.
    String str = null;
    String line;
    while((line = br.readLine()) != null){
        str += line;
    }
    System.out.println(str);
Run Code Online (Sandbox Code Playgroud)

这是错误消息。

线程“main”java.io.IOException 中出现异常:服务器返回 HTTP 响应代码:400 对于 URL: https: //graph.microsoft.com/v1.0/me

但是,这个访问令牌是在Java中获取的,与其他程序一起使用时它可以正常工作。

这是我的 PowerShell 源代码。(我得到了预期的结果。)

$response = Invoke-RestMethod `
  -Uri ( "https://graph.microsoft.com/v1.0/me" ) `
  -Method Get `
  -Headers @{
      Authorization = "Bearer EwA4A8l6BA...";
  } `
  -ErrorAction Stop;
Run Code Online (Sandbox Code Playgroud)

这是什么原因呢?以及如何修复它?

Smd*_*Smd 5

对不起。我自己解决了我的问题。出现这个问题是因为我的服务器不接受 json 响应。

因此,我在请求标头中添加了“Accept:application/json”。

因此,这是正确的源代码。

    HttpURLConnection con = null;
    String url_str = "https://graph.microsoft.com/v1.0/me";
    String bearer_token = "EwA4A8l6BA...";

    URL url = new URL(url_str);
    con = ( HttpURLConnection )url.openConnection();
    con.setDoInput(true);
    con.setDoOutput(true);
    con.setUseCaches(false);
    con.setRequestMethod("GET");
    con.setRequestProperty("Authorization","Bearer " + bearer_token);
    con.setRequestProperty("Accept","application/json"); // I added this line.
    con.connect();

    BufferedReader br = new BufferedReader(new InputStreamReader( con.getInputStream() ));
    String str = null;
    String line;
    while((line = br.readLine()) != null){
        str += line;
    }
    System.out.println(str);
Run Code Online (Sandbox Code Playgroud)

我希望这篇文章对某人有所帮助。