【问题标题】:When I use an access token of Microsoft Graph, Access failed and response 400 error当我使用 Microsoft Graph 的访问令牌时,访问失败并响应 400 错误
【发布时间】:2017-12-19 03:17:27
【问题描述】:

我尝试在 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);

这是错误信息。

线程“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;

这是什么原因?以及如何解决?

【问题讨论】:

    标签: java microsoft-graph-api


    【解决方案1】:

    对不起。我自己解决了我的问题。 出现这个问题,我的服务器不接受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);
    

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

    【讨论】:

      猜你喜欢
      • 2016-10-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-11-26
      • 1970-01-01
      • 1970-01-01
      • 2022-01-12
      • 1970-01-01
      相关资源
      最近更新 更多