当前位置: 首页 > 知识库问答 >
问题:

谷歌日历APIJava 400 invalid_request

汲品
2023-03-14
@Component
public class GoogleCalendarSyncListener implements ApplicationListener<CourseLessonGoogleCalendarNeedToBeUpdatedEvent> {

    private String getEventId(Lesson parameter) { // encapsulator method
        return "cita" + parameter.getId();
    }

    // TODO bu daha genel olabilir.
    @Configuration
    static class Configurator {
        @Bean
        public Calendar client() {
            List<String> scopes = Lists.newArrayList(CalendarScopes.CALENDAR);
            try {
                Calendar client = CalendarUtils.createCalendarClient(scopes);
                return client;
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
    }

    private final Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private LessonService lessonService;
    @Autowired
    private LessonUserService lessonUserService;
    @Autowired
    private Calendar client; // bunu da confige taşımak lazım

    @Override
    public void onApplicationEvent(CourseLessonGoogleCalendarNeedToBeUpdatedEvent courseLessonGoogleCalendarNeedToBeUpdatedEvent) {

        try {
            ProductType productType = courseLessonGoogleCalendarNeedToBeUpdatedEvent.getCourseRegistration().getCourse().getCategory().getProductType();
            Course course = courseLessonGoogleCalendarNeedToBeUpdatedEvent.getCourseRegistration().getCourse();
            List<Lesson> lessons = lessonService.loadLessonsByCourse(course);

            int lessonCount = lessons.size();

            for (Lesson lesson : lessons) {
                String description = "";
                try {
                    String eventId = getEventId(lesson);  // RFC2938 bu kurala uygun olmalı
                    DateTime start = new DateTime(lesson.getDate(), TimeZone.getTimeZone("UTC+03:00"));
                    java.util.Calendar cal = java.util.Calendar.getInstance();
                    cal.setTime(lesson.getDate());
                    cal.add(java.util.Calendar.MINUTE, lesson.getLessonPricingTemplate().getDurationMinutes());
                    cal.getTime();
                    DateTime end = new DateTime(cal.getTime(), TimeZone.getTimeZone("UTC+03:00"));

                    description  += lesson.getCourse().getCatName();

                    String color = "";

                    for (LessonUser lessonuser : lessonUserService.loadByLesson(lesson)) {
                        description +=  " " + lessonuser.getUser().getPrettyName();
                        switch (lessonuser.getUser().getUsername()) {
                            case "bgor":
                                color = Constants.BGORCOLOR;
                                break;
                        }
                    }
                    // TODO error checdking

                    description += lessonService.lessonIndex(lesson) + "/" + lessonCount;

                    Event event = new Event();
                    event.setColorId(color);
                    event.setId(eventId);
                    event.setReminders(new Event.Reminders().setUseDefault(false));
                    event.setSummary(description);
                    event.setStart(new EventDateTime().setDateTime(start));
                    event.setEnd(new EventDateTime().setDateTime(end));
                    event.setDescription(lesson.getCourse().getCatName());

                    List<EventAttendee> attendees = new ArrayList<>();
                    EventAttendee admin = new EventAttendee();
                    admin.setEmail("mail@btmuzik.com");
                    attendees.add(admin);

                    List<LessonUser> lessonUsers = lessonUserService.loadByLesson(lesson);
                    lessonUsers.forEach(lu -> {
                        EventAttendee attendee = new EventAttendee();
                        if (lu.getUser().getEmail() != null) {
                            attendee.setEmail(lu.getUser().getEmail());
                            attendees.add(attendee);
                        }
                    });

                    event.setAttendees(attendees);

                    Event.Creator creator = new Event.Creator();
                    Event.Organizer organizer = new Event.Organizer();
                    creator.setEmail("mail@btmuzik.com");
                    organizer.setEmail("mail@btmuzik.com");
                    event.setCreator(creator);
                    event.setOrganizer(organizer);

                    logger.info("event %s (%s)\n", event.getSummary(), start);

                    saveOrUpdateEvent(event);

                } catch (Exception e) {
                    logger.error(e.getMessage(), e);
                }
            }

        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
    }

    // By existing conf tomcat/.store/bt-calendar-sync/StoredCredentials must exist
    // These are copy of  btmuzikevi-parent/tokens/StoredCredential  created by CalendarReader

    private Event saveOrUpdateEvent(Event event) {
        try {
            System.out.println("client = " + client.getBaseUrl());
            System.out.println("client = " + client.getRootUrl());
            System.out.println("event.getId() = " + event.getId());

            List<String> scopes = Lists.newArrayList(CalendarScopes.CALENDAR);
            client = CalendarUtils.createCalendarClient(scopes);
            Calendar.Events.List request = client.events().list("primary");

            System.out.println("--------------------------------- ");

            event = client.events().update("primary", event.getId(), event).execute(); // updated event
            System.out.println(event.getId()+ " HUHA = " + event.getStart());
            return event;
        } catch (GoogleJsonResponseException e) { // burası özel bir değer veriyor
            try {
                event = client.events().insert("primary", event).execute();
                return event;
            } catch (IOException ioException) { // bu çok özel değil ama tüm detayı içeriyor
                throw new RuntimeException(ioException); // tamamını runtimeexception olarak dönüyoruz.
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
  • 谷歌日历API…/auth/Calendar查看、编辑、共享和永久删除您可以使用谷歌日历访问的所有日历
  • 谷歌日历API…/auth/Calendar。acls查看并更改您拥有的Google日历的共享权限
  • 谷歌日历API…/auth/Calendar。事件查看和编辑所有日历上的事件

CalendarQuickstart或CalendarReader很好,它们从日历中读取,但:当我尝试写入日历时,我得到:

授权错误错误 400:缺少invalid_request必需参数:response_type

我错过了什么?预先感谢任何帮助

共有1个答案

乐正心水
2023-03-14

如果您收到该消息,那么您对库进行身份验证的方式存在重大错误。我所知道的关于Java与google api Java客户端库的最佳教程是针对google分析的教程

我试着帮你翻译成日历,应该很接近。

/**
 * A simple example of how to access the Google Calendar API.
 */
public class HelloCalendar {
  // Path to client_secrets.json file downloaded from the Developer's Console.
  // The path is relative to HelloAnalytics.java.
  private static final String CLIENT_SECRET_JSON_RESOURCE = "client_secrets.json";

  // Replace with your view ID.
  private static final String VIEW_ID = "<REPLACE_WITH_VIEW_ID>";

  // The directory where the user's credentials will be stored.
  private static final File DATA_STORE_DIR = new File(
      System.getProperty("user.home"), ".store/hello_calendar");

  private static final String APPLICATION_NAME = "Hello Calendar";
  private static final JsonFactory JSON_FACTORY = GsonFactory.getDefaultInstance();
  private static NetHttpTransport httpTransport;
  private static FileDataStoreFactory dataStoreFactory;

  public static void main(String[] args) {
    try {
      Calendar service = initializeCalendarReporting();

      // make call here
    } catch (Exception e) {
      e.printStackTrace();
    }
  }


  /**
   * Initializes an authorized Calendar service object.
   *
   * @return The Calendar service object.
   * @throws IOException
   * @throws GeneralSecurityException
   */
  private static Calendar initializeCalendar() throws GeneralSecurityException, IOException {

    httpTransport = GoogleNetHttpTransport.newTrustedTransport();
    dataStoreFactory = new FileDataStoreFactory(DATA_STORE_DIR);

    // Load client secrets.
    GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JSON_FACTORY,
        new InputStreamReader(HelloCalendar.class
            .getResourceAsStream(CLIENT_SECRET_JSON_RESOURCE)));

    // Set up authorization code flow for all authorization scopes.
    GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow
        .Builder(httpTransport, JSON_FACTORY, clientSecrets,
            CalendarScopes.all()).setDataStoreFactory(dataStoreFactory)
        .build();

    // Authorize.
    Credential credential = new AuthorizationCodeInstalledApp(flow,
        new LocalServerReceiver()).authorize("user");
    // Construct the Calendar service object.
    return new Calendar.Builder(httpTransport, JSON_FACTORY, credential)
        .setApplicationName(APPLICATION_NAME).build();
  }
 类似资料:
  • 在使用GoogleCalendarAPI(与python一起使用)时,我已经能够获得我想要的变量,因此我可以将事件导出到文本文件中。然而,一个变量(位置)触发了一个错误,我不知道为什么。 这直接来自google的开始代码,我还添加了我想要的变量: 它会打印一个即将到来的约会列表,包括地点,但它会停止并向我抛出这个错误 这是凭据/json的问题吗?我使用的是谷歌日历api的旧版本吗?我怎么检查?我的

  • 我想知道我是否需要Google java客户端库才能从GAE访问我的Google日历。默认情况下,它们是Google App Engine SDK的一部分吗? 此外,我找不到一个很好的示例或教程来展示如何从Google Cloud Platform应用程序创建、读取、更新和删除Google日历事件。 非常感谢,如果您可以提供相同的代码示例或链接到适当的工作教程。

  • 是否有人有链接或可以提供Java谷歌应用程序引擎项目的代码,该项目只是与谷歌日历交互。假设从日历中获取活动。 Google Sample calendar-app engine-Sample在从HG检出后无法编译,我曾尝试搜索教程并创建自己的教程,只是运气好而已。 我已经设置了一个 API 访问项目来获取客户端机密.json。

  • 只用我的日历ID工作得很好. en.thai#holiday@group.v3.calendar.google.com |en.th#holiday@group.v3.calendar.google.com | 请帮忙谢谢你 calenderId:“me”或“primary………..output:”所有事件列表“ 日历Id:en.th#holiday@group.v3.calendar.googl

  • 我有一个应用程序使用s2s与谷歌日历API的连接。我需要在不同的用户日历中创建事件。若要使之成为可能,用户应转到日历的设置并将其日历共享到服务帐户。但我想为用户简化这一点 - 这样他们就不需要去他们的日历设置。我没有用于用户交互的界面 - 这是一个机器人。如何以其他方式访问用户的日历?

  • 我希望我的应用在用户的 Google 日历上添加/删除/更新事件。应用只需删除和更新应用本身已添加的事件。 我是否正确地理解了这一点,为了使其正常工作,用户必须向应用程序授予对其Google日历的完全访问权限,这意味着该应用程序可能会读取和删除任何日历上的私人事件? 或者,有没有办法限制用户对应用程序的访问权限,例如,允许应用程序创建单个日历,只允许它访问该日历上的事件? 我已经通读了相关的谷歌日