如何使用Microsoft Graph API获取事件列表?Android端实现咨询
嘿,我来一步步教你在Android上用Microsoft Graph获取已登录用户的事件列表,结合你已经配置的权限和URL,咱们直接上手实操:
一、先确认基础配置(你已经做了,但再核对下更稳妥)
- 权限配置:你定义的
SCOPES里已经包含了Calendars.Read、Calendars.ReadWrite这类必要的日历权限,完全没问题!不过要确保Azure AD应用后台里,这些权限是委派权限,并且如果是企业租户用户,管理员已经同意了这些权限哦。 - 身份认证:调用Graph API的前提是拿到有效的访问令牌,你应该已经通过MSAL(Microsoft Authentication Library)完成了用户登录,记得后续请求要带上这个令牌。
二、调用Graph API获取事件列表
1. 完善API请求URL
你写的CALENDER_URL可以再优化下,明确指定需要返回的字段,减少不必要的数据传输,比如:
final static String CALENDER_URL = "https://graph.microsoft.com/v1.0/me/events?$select=subject,start,end,bodyPreview,id";
这里$select指定了返回事件的主题、开始/结束时间、内容预览和事件ID,足够用来展示列表了。如果需要更多字段,直接在后面加就行,比如location。
2. 用Retrofit发送请求(推荐,也可以用OkHttp)
第一步:定义Graph服务接口
public interface GraphCalendarService { @GET Call<EventListResponse> getUserEvents(@Url String requestUrl, @Header("Authorization") String authHeader); }
第二步:定义数据模型(用来解析返回的JSON)
// 外层响应模型 public class EventListResponse { public List<CalendarEvent> value; } // 单个事件模型 public class CalendarEvent { public String id; public String subject; public EventDateTime start; public EventDateTime end; public String bodyPreview; // 时间子模型 public static class EventDateTime { public String dateTime; public String timeZone; } }
第三步:发送请求并处理响应
// 先从MSAL获取访问令牌(这个是你已经实现的登录后获取令牌的方法) String accessToken = getCurrentAccessToken(); // 构建Retrofit实例 Retrofit retrofit = new Retrofit.Builder() .baseUrl("https://graph.microsoft.com/v1.0/") .addConverterFactory(GsonConverterFactory.create()) .build(); GraphCalendarService calendarService = retrofit.create(GraphCalendarService.class); Call<EventListResponse> call = calendarService.getUserEvents(CALENDER_URL, "Bearer " + accessToken); // 异步请求,避免阻塞UI线程 call.enqueue(new Callback<EventListResponse>() { @Override public void onResponse(Call<EventListResponse> call, Response<EventListResponse> response) { if (response.isSuccessful()) { List<CalendarEvent> eventList = response.body().value; // 拿到事件列表啦,接下来就可以把数据绑定到RecyclerView之类的UI控件上展示 updateEventListUI(eventList); } else { // 处理API错误,比如令牌过期、权限不足 handleGraphApiError(response); } } @Override public void onFailure(Call<EventListResponse> call, Throwable t) { // 处理网络连接错误,比如无网络、超时 t.printStackTrace(); showNetworkErrorToast(); } });
三、常见问题排查
- 401 Unauthorized:大概率是访问令牌过期了,试试调用MSAL的静默刷新令牌方法,如果刷新失败,引导用户重新登录。
- 403 Forbidden:检查Azure AD应用里的权限是否真的被授予,或者当前登录的用户有没有访问自己日历的权限。
- 返回事件为空:要么用户日历里确实没事件,要么可以加
$filter参数筛选时间范围,比如$filter=start/dateTime ge '2024-05-01T00:00:00Z'来获取5月1日之后的事件。
内容的提问来源于stack exchange,提问作者urnish
相关产品推荐
相关产品推荐

