【发布时间】: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;
这是什么原因?以及如何解决?
【问题讨论】: