我尝试在Java上使用Microsoft Graph。我成功获得了一个访问令牌。
但是,当我通过HttpURLConnection使用此令牌时,我的访问被拒绝并从微软服务器收到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;
这是什么原因?以及如何解决它?
答案 0 :(得分: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);
我希望这篇文章可以帮助别人。