管理课程邀请

Google 课堂中的邀请资源表示邀请用户以特定课程角色加入课程。

每个邀请资源都包含以下字段:

  • 由 Google 课堂分配的邀请的 id
  • 发送邀请的用户的 userId
  • 用户受邀加入的课程的 courseId
  • role 受邀用户在课程中的课程角色

创建邀请

创建邀请,以便用户通过调用 invitations.create() 方法以指定角色加入课程。在请求正文中添加邀请资源,并指定 courseIduserIdrole

Java

classroom/snippets/src/main/java/CreateInvitation.java
Invitation invitation = null;
try {
  /* Set the role the user is invited to have in the course. Possible values of CourseRole can be
  found here: https://developers.google.com/classroom/reference/rest/v1/invitations#courserole.*/
  Invitation content =
      new Invitation().setCourseId(courseId).setUserId(userId).setRole("TEACHER");

  invitation = service.invitations().create(content).execute();

  System.out.printf(
      "User (%s) has been invited to course (%s).\n",
      invitation.getUserId(), invitation.getCourseId());
} catch (GoogleJsonResponseException e) {
  // TODO (developer) - handle error appropriately
  GoogleJsonError error = e.getDetails();
  if (error.getCode() == 404) {
    System.out.printf("The course or user does not exist.\n");
  }
  throw e;
} catch (Exception e) {
  throw e;
}
return invitation;

检索邀请

通过调用 invitations.get() 方法并指定邀请的 id 来检索特定邀请。

Java

classroom/snippets/src/main/java/GetInvitation.java
Invitation invitation = null;
try {
  invitation = service.invitations().get(id).execute();
  System.out.printf(
      "Invitation (%s) for user (%s) in course (%s) retrieved.\n",
      invitation.getId(), invitation.getUserId(), invitation.getCourseId());
} catch (GoogleJsonResponseException e) {
  GoogleJsonError error = e.getDetails();
  if (error.getCode() == 404) {
    System.out.printf("The invitation id (%s) does not exist.\n", id);
  }
  throw e;
} catch (Exception e) {
  throw e;
}
return invitation;

接受邀请

接受课程邀请会删除邀请,并将用户添加到课程中,并为其分配邀请中指定的角色。通过调用 invitations.accept() 方法并指定邀请的 id 来接受邀请。

Java

classroom/snippets/src/main/java/AcceptInvitation.java
try {
  service.invitations().accept(id).execute();
  System.out.printf("Invitation (%s) was accepted.\n", id);
} catch (GoogleJsonResponseException e) {
  GoogleJsonError error = e.getDetails();
  if (error.getCode() == 404) {
    System.out.printf("The invitation id (%s) does not exist.\n", id);
  }
  throw e;
} catch (Exception e) {
  throw e;
}

删除邀请

更新邀请的唯一方法是将其删除并创建新的邀请。如需删除邀请,请调用 invitations.delete() 方法并指定 id

Java

classroom/snippets/src/main/java/DeleteInvitation.java
try {
  service.invitations().delete(id).execute();
  System.out.printf("Invitation (%s) was deleted.\n", id);
} catch (GoogleJsonResponseException e) {
  GoogleJsonError error = e.getDetails();
  if (error.getCode() == 404) {
    System.out.printf("The invitation id (%s) does not exist.\n", id);
  }
  throw e;
} catch (Exception e) {
  throw e;
}