java - 使用 Azure 门户中的 Web 应用程序凭据访问 Java 中的 Microsoft Graph Rest 服务

标签 java rest spring-mvc microsoft-graph-api

我正在尝试通过 Microsoft Graph Api 访问以下网址:- https://graph.microsoft.com/v1.0/me 我使用了在 stackoverflow 上找到的下面给出的代码,理想情况下它应该给我 JSON。但我在运行代码时遇到异常:-

try {
            String url_str = "https://graph.microsoft.com/v1.0/me";
            String access_token = getAccessToken();

            url = new URL(url_str);
            con = ( HttpURLConnection )url.openConnection();
            con.setDoInput(true);
            con.setDoOutput(true);
            con.setUseCaches(false);
            con.setRequestMethod("GET");
            con.setRequestProperty("Authorization", access_token);
            con.setRequestProperty("Accept","application/json");
            con.connect();

            br = new BufferedReader(new InputStreamReader( con.getInputStream() ));
            String str = null;
            String line;
            while((line = br.readLine()) != null){
                str += line;
            }
            System.out.println(str);
        } catch (Exception e) {
            e.printStackTrace();
        }

我正在获取有效的访问 token 。但我遇到以下异常:-

java.io.FileNotFoundException: https://graph.microsoft.com/v1.0/me
    at sun.net.www.protocol.http.HttpURLConnection.getInputStream0(Unknown Source)
    at sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown Source)
    at sun.net.www.protocol.https.HttpsURLConnectionImpl.getInputStream(Unknown Source)
    at com.controller.MicrosoftGraphController.getUserInfo(MicrosoftGraphController.java:50)
    at com.controller.MicrosoftGraphController.main(MicrosoftGraphController.java:82)

我尝试搜索,但没有找到与此特定问题相关的任何内容。有什么建议么?谢谢!

最佳答案

将代码更改为:

con.setRequestProperty("Authorization", "Bearer " + access_token);

您正在使用 OAuth2 协议(protocol),它需要的不仅仅是原始 token 。请注意代码中“Bearer”一词后面的空格字符。

看看the docs了解更多详情。

关于java - 使用 Azure 门户中的 Web 应用程序凭据访问 Java 中的 Microsoft Graph Rest 服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48755076/

相关文章:

java - 如何在同一项目中连接两个数据库 MySQL 和 MongoDB?是否可以?

php - Newsletter2Go REST API - 如何将新收件人添加到列表中?

java - 使用不可序列化对象将类保存到文件

java - Android Gradle 插件需要 Java 11 才能运行。您当前使用的是 Java 1.8

java.lang.IllegalArgumentException : No matching constant for [0] while using RestTemplate

rest - 如何在不实际执行的情况下模拟 HTTP DELETE 操作的后果

.net - 使用 REST API 的 Paypal 快速结账

java - Spring MVC : large files for download, OutOfMemoryException

java - Thymeleaf 在对象列表上进行多重选择

java - 如何从 maven 命令行远程调试 java 应用程序