Java create microsoft graph client

分享四步用java创建microsoft graph client,具体如下:

一、需要的类

1.1jackson-core-2.14.1jar

1.2jackson-databind-2.14.1.jar

1.3microsoft-graph-5.49.0.jar

1.4microsoft-graph-core-2.0.16.jar

1.5okhttp-4.10.0.jar

1.6gson-2.10.1.jar

1.7guava-jdk5-13.0.jar

1.8kotlin-stdlib-1.8.10.jar

1.9okio-2.1.0.jar

二、申请Micosoft Application授权

参考URL:https://learn.microsoft.com/zh-cn/azure/active-directory/reports-monitoring/howto-configure-prerequisites-for-reporting-api

此步骤获取到如下参数

2.1 tenantId //租户ID

2.2 clientId //客户端Id

2.3 clientSecret //客户端密码

三、获取访问Token

private staticString getAccessToken(){

String sReturn = "";

String tenantId ="XXX";

String clientId = "XXX";

String clientSecret = "xxx";

String authUrl = "https://login.microsoftonline.com/"+ tenantId + "/oauth2/token";

try{

URL url = new URL(authUrl);

HttpURLConnection conn =(HttpURLConnection) url.openConnection();

conn.setRequestMethod("POST");

conn.setRequestProperty("Content-Type","application/x-www-form-urlencoded");

conn.setDoOutput(true);

OutputStreamWriter out = newOutputStreamWriter(conn.getOutputStream());

String postData ="grant_type=client_credentials"

+ "&client_id=" +clientId

+"&client_secret=" + clientSecret

+"&resource=https://graph.microsoft.com";

out.write(postData);

out.close();

BufferedReader in = newBufferedReader(new InputStreamReader(conn.getInputStream()));

String inputLine;

StringBuffer response = newStringBuffer();

while ((inputLine = in.readLine())!= null) {

response.append(inputLine);

}

in.close();

String json = response.toString();

Map<String, Object> map = newHashMap<>();

map = newObjectMapper().readValue(json, new TypeReference<Map<String,Object>>() {});

sReturn = (String)map.get("access_token");

}catch(Exception e){

System.out.println("getAccessToken get error is : " + e);

}

return sReturn;

}

四、创建Microsoft graph client

private staticGraphServiceClient getGraphClient() {

GraphServiceClient graphClient = null;

try{

IAuthenticationProviderauthProvider = new IAuthenticationProvider() {

@Override

publicCompletableFuture<String> getAuthorizationTokenAsync(URL requestUrl) {

CompletableFuture<String> future = newCompletableFuture<>();

try{

future.complete(getAccessToken());

}catch(Exception e){

System.out.println("getAuthorizationTokenAsync get error is :" + e);

}

return future;

}

};

graphClient =GraphServiceClient.builder().authenticationProvider(authProvider).buildClient();

}catch(Exception e){

System.out.println("get erroris : " + e);

}

return graphClient;

}

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值