คู่มือเริ่มต้นใช้งาน Java

สร้างแอปพลิเคชันบรรทัดคำสั่ง Java ที่ส่งคำขอไปยัง Google Calendar API

คู่มือเริ่มต้นใช้งานฉบับย่อจะอธิบายวิธีตั้งค่าและเรียกใช้แอปที่เรียกใช้ Google Workspace API โดยคู่มือเริ่มต้นใช้งานฉบับย่อนี้ใช้วิธีการตรวจสอบสิทธิ์แบบง่ายซึ่งเหมาะกับสภาพแวดล้อมการทดสอบ สำหรับสภาพแวดล้อมการใช้งานจริง เราขอแนะนำให้คุณศึกษาเกี่ยวกับ การตรวจสอบสิทธิ์และการให้สิทธิ์ ก่อน เลือกข้อมูลเข้าสู่ระบบ ที่เหมาะสมกับแอป

คู่มือเริ่มต้นใช้งานฉบับย่อนี้ใช้ไลบรารีไคลเอ็นต์ API ที่ Google Workspace แนะนำเพื่อจัดการรายละเอียดบางอย่างของขั้นตอนการตรวจสอบสิทธิ์และการให้สิทธิ์

วัตถุประสงค์

  • ตั้งค่าสภาพแวดล้อม
  • ตั้งค่าตัวอย่าง
  • เรียกใช้ตัวอย่าง

ข้อกำหนดเบื้องต้น

  • บัญชี Google ที่เปิดใช้ Google ปฏิทิน

ตั้งค่าสภาพแวดล้อม

ตั้งค่าสภาพแวดล้อมให้พร้อมเพื่อทำตามคู่มือเริ่มต้นใช้งานฉบับย่อนี้

เปิดใช้ API

ก่อนใช้ Google API คุณต้องเปิด API เหล่านั้นในโปรเจ็กต์ Google Cloud โดยคุณสามารถเปิด API อย่างน้อย 1 รายการในโปรเจ็กต์ Google Cloud เดียว

หากใช้โปรเจ็กต์ Google Cloud ใหม่เพื่อทำตามคู่มือเริ่มต้นใช้งานฉบับย่อนี้ ให้กำหนดค่าหน้าจอขอคำยินยอม OAuth หากทำขั้นตอนนี้สำหรับโปรเจ็กต์ Cloud แล้ว ให้ข้ามไปยังส่วนถัดไป

  1. ใน Google API Console ให้ไปที่เมนู > แพลตฟอร์มการตรวจสอบสิทธิ์ของ Google > การสร้างแบรนด์

    ไปที่การสร้างแบรนด์

  2. หากกำหนดค่าแพลตฟอร์มการตรวจสอบสิทธิ์ของ Google ไว้แล้ว คุณสามารถกำหนดค่าการตั้งค่าหน้าจอขอคำยินยอม OAuth ต่อไปนี้ใน การสร้างแบรนด์, กลุ่มเป้าหมาย และ การเข้าถึงข้อมูล หากเห็นข้อความว่า Google Auth platform not configured yet (ยังไม่ได้กำหนดค่าแพลตฟอร์มการตรวจสอบสิทธิ์ของ Google) ให้คลิก Get Started (เริ่มต้นใช้งาน)
    1. ในส่วนข้อมูลแอป ให้ป้อนชื่อแอปในช่องชื่อแอป
    2. ในส่วนอีเมลสนับสนุนสำหรับผู้ใช้ ให้เลือกอีเมลสนับสนุนที่ผู้ใช้สามารถติดต่อคุณได้หากมีคำถามเกี่ยวกับคำยินยอม
    3. คลิกถัดไป
    4. ในส่วนกลุ่มเป้าหมาย ให้เลือกภายใน
    5. คลิกถัดไป
    6. ในส่วนข้อมูลติดต่อ ให้ป้อนอีเมล ที่คุณจะได้รับการแจ้งเตือนเกี่ยวกับการเปลี่ยนแปลงในโปรเจ็กต์
    7. คลิกถัดไป
    8. ในส่วนเสร็จสิ้น ให้อ่านนโยบายข้อมูลผู้ใช้สำหรับบริการ Google API และหากยอมรับ ให้เลือกฉันยอมรับบริการ Google API: นโยบายข้อมูลผู้ใช้
    9. คลิกต่อไป
    10. คลิกสร้าง
  3. ตอนนี้คุณสามารถข้ามการเพิ่มขอบเขตได้ ในอนาคต เมื่อสร้างแอปเพื่อใช้ภายนอกองค์กร Google Workspace คุณต้องเปลี่ยนประเภทผู้ใช้ เป็นภายนอก จากนั้น เพิ่มขอบเขตการให้สิทธิ์ที่แอปต้องการ ดูข้อมูลเพิ่มเติมได้ที่คู่มือฉบับเต็มเกี่ยวกับการกำหนดค่าคำยินยอม OAuth

ให้สิทธิ์ข้อมูลเข้าสู่ระบบสำหรับแอปพลิเคชันบนเดสก์ท็อป

หากต้องการตรวจสอบสิทธิ์ผู้ใช้ปลายทางและเข้าถึงข้อมูลผู้ใช้ในแอป คุณต้องสร้างรหัสไคลเอ็นต์ OAuth 2.0 อย่างน้อย 1 รายการ รหัสไคลเอ็นต์ใช้เพื่อระบุแอปเดี่ยวไปยังเซิร์ฟเวอร์ OAuth ของ Google หากแอปทำงานบนหลายแพลตฟอร์ม คุณต้องสร้างรหัสไคลเอ็นต์แยกต่างหากสำหรับแต่ละแพลตฟอร์ม
  1. ในคอนโซล Google Cloud ให้ไปที่เมนู > แพลตฟอร์มการตรวจสอบสิทธิ์ของ Google > ไคลเอ็นต์

    ไปที่ไคลเอ็นต์

  2. คลิกสร้างไคลเอ็นต์
  3. คลิกประเภทแอปพลิเคชัน > แอปบนเดสก์ท็อป
  4. พิมพ์ชื่อของข้อมูลเข้าสู่ระบบในช่องชื่อ ชื่อนี้จะแสดงในคอนโซล Google Cloud เท่านั้น
  5. คลิกสร้าง

    ข้อมูลเข้าสู่ระบบที่สร้างขึ้นใหม่จะปรากฏในส่วน "รหัสไคลเอ็นต์ OAuth 2.0"

  6. บันทึกไฟล์ JSON ที่ดาวน์โหลดเป็น credentials.json แล้วย้ายไฟล์ไปยังไดเรกทอรีงาน

เตรียมพื้นที่ทำงาน

  1. สร้างโครงสร้างโปรเจ็กต์ใหม่ในไดเรกทอรีงานโดยทำดังนี้

    gradle init --type basic
    mkdir -p src/main/java src/main/resources 
    
  2. ในไดเรกทอรี src/main/resources/ ให้คัดลอกไฟล์ credentials.json ที่ดาวน์โหลดไว้ก่อนหน้านี้

  3. เปิดไฟล์ build.gradle เริ่มต้น แล้วแทนที่เนื้อหาด้วยโค้ดต่อไปนี้

    calendar/quickstart/build.gradle
    apply plugin: 'java'
    apply plugin: 'application'
    
    mainClassName = 'CalendarQuickstart'
    sourceCompatibility = 11
    targetCompatibility = 11
    version = '1.0'
    
    repositories {
        mavenCentral()
    }
    
    dependencies {
        implementation 'com.google.api-client:google-api-client:2.0.0'
        implementation 'com.google.oauth-client:google-oauth-client-jetty:1.34.1'
        implementation 'com.google.apis:google-api-services-calendar:v3-rev20220715-2.0.0'
    }

ตั้งค่าตัวอย่าง

  1. ในไดเรกทอรี src/main/java/ ให้สร้างไฟล์ Java ใหม่ที่มีชื่อตรงกับค่า mainClassName ในไฟล์ build.gradle

  2. ใส่โค้ดต่อไปนี้ในไฟล์ Java ใหม่

    calendar/quickstart/src/main/java/CalendarQuickstart.java
    import com.google.api.client.auth.oauth2.Credential;
    import com.google.api.client.extensions.java6.auth.oauth2.AuthorizationCodeInstalledApp;
    import com.google.api.client.extensions.jetty.auth.oauth2.LocalServerReceiver;
    import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeFlow;
    import com.google.api.client.googleapis.auth.oauth2.GoogleClientSecrets;
    import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
    import com.google.api.client.http.javanet.NetHttpTransport;
    import com.google.api.client.json.JsonFactory;
    import com.google.api.client.json.gson.GsonFactory;
    import com.google.api.client.util.DateTime;
    import com.google.api.client.util.store.FileDataStoreFactory;
    import com.google.api.services.calendar.Calendar;
    import com.google.api.services.calendar.CalendarScopes;
    import com.google.api.services.calendar.model.Event;
    import com.google.api.services.calendar.model.Events;
    
    import java.io.FileNotFoundException;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.InputStreamReader;
    import java.security.GeneralSecurityException;
    import java.util.Collections;
    import java.util.List;
    
    /* class to demonstrate use of Calendar events list API */
    public class CalendarQuickstart {
      /**
       * Application name.
       */
      private static final String APPLICATION_NAME = "Google Calendar API Java Quickstart";
      /**
       * Global instance of the JSON factory.
       */
      private static final JsonFactory JSON_FACTORY = GsonFactory.getDefaultInstance();
      /**
       * Directory to store authorization tokens for this application.
       */
      private static final String TOKENS_DIRECTORY_PATH = "tokens";
    
      /**
       * Global instance of the scopes required by this quickstart.
       * If modifying these scopes, delete your previously saved tokens/ folder.
       */
      private static final List<String> SCOPES =
          Collections.singletonList(CalendarScopes.CALENDAR_READONLY);
      private static final String CREDENTIALS_FILE_PATH = "/credentials.json";
    
      /**
       * Creates an authorized Credential object.
       *
       * @param HTTP_TRANSPORT The network HTTP Transport.
       * @return An authorized Credential object.
       * @throws IOException If the credentials.json file cannot be found.
       */
      private static Credential getCredentials(final NetHttpTransport HTTP_TRANSPORT)
          throws IOException {
        // Load client secrets.
        InputStream in = CalendarQuickstart.class.getResourceAsStream(CREDENTIALS_FILE_PATH);
        if (in == null) {
          throw new FileNotFoundException("Resource not found: " + CREDENTIALS_FILE_PATH);
        }
        GoogleClientSecrets clientSecrets =
            GoogleClientSecrets.load(JSON_FACTORY, new InputStreamReader(in));
    
        // Build flow and trigger user authorization request.
        GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
            HTTP_TRANSPORT, JSON_FACTORY, clientSecrets, SCOPES)
            .setDataStoreFactory(new FileDataStoreFactory(new java.io.File(TOKENS_DIRECTORY_PATH)))
            .setAccessType("offline")
            .build();
        LocalServerReceiver receiver = new LocalServerReceiver.Builder().setPort(8888).build();
        Credential credential = new AuthorizationCodeInstalledApp(flow, receiver).authorize("user");
        //returns an authorized Credential object.
        return credential;
      }
    
      public static void main(String... args) throws IOException, GeneralSecurityException {
        // Build a new authorized API client service.
        final NetHttpTransport HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport();
        Calendar service =
            new Calendar.Builder(HTTP_TRANSPORT, JSON_FACTORY, getCredentials(HTTP_TRANSPORT))
                .setApplicationName(APPLICATION_NAME)
                .build();
    
        // List the next 10 events from the primary calendar.
        DateTime now = new DateTime(System.currentTimeMillis());
        Events events = service.events().list("primary")
            .setMaxResults(10)
            .setTimeMin(now)
            .setOrderBy("startTime")
            .setSingleEvents(true)
            .execute();
        List<Event> items = events.getItems();
        if (items.isEmpty()) {
          System.out.println("No upcoming events found.");
        } else {
          System.out.println("Upcoming events");
          for (Event event : items) {
            DateTime start = event.getStart().getDateTime();
            if (start == null) {
              start = event.getStart().getDate();
            }
            System.out.printf("%s (%s)\n", event.getSummary(), start);
          }
        }
      }
    }

เรียกใช้ตัวอย่าง

  1. เรียกใช้ตัวอย่างโดยทำดังนี้

    gradle run
    
  1. เมื่อเรียกใช้ตัวอย่างเป็นครั้งแรก ระบบจะแจ้งให้คุณให้สิทธิ์เข้าถึง โดยให้ทำดังนี้
    1. หากยังไม่ได้ลงชื่อเข้าใช้บัญชี Google ให้ลงชื่อเข้าใช้เมื่อได้รับข้อความแจ้ง หากลงชื่อเข้าใช้ไว้หลายบัญชี ให้เลือกบัญชีที่จะใช้ในการให้สิทธิ์
    2. คลิกยอมรับ

    แอปพลิเคชัน Java จะทำงานและเรียกใช้ Google Calendar API

    ระบบจะจัดเก็บข้อมูลการให้สิทธิ์ไว้ในระบบไฟล์ ดังนั้นเมื่อเรียกใช้โค้ดตัวอย่างในครั้งถัดไป ระบบจะไม่แจ้งให้คุณให้สิทธิ์

ขั้นตอนถัดไป