자바 언어 가이드

중요: 이 문서는 2012년 이전에 작성되었습니다. 이 문서에 설명된 인증 옵션 (OAuth 1.0, AuthSub, ClientLogin)은 2012년 4월 20일부로 공식적으로 지원 중단되었으며 더 이상 사용할 수 없습니다. 가능한 한 빨리 OAuth 2.0으로 이전하는 것이 좋습니다.

Google Sites Data API를 사용하면 클라이언트 애플리케이션에서 Google Sites 내의 콘텐츠에 액세스하고 이를 게시 및 수정할 수 있습니다. 또한 클라이언트 애플리케이션에서는 최근 활동 목록을 요청하고, 업데이트 기록을 가져오고, 첨부파일을 다운로드할 수 있습니다.

이 가이드에서는 Sites Data API의 기능에 대한 배경 지식 외에 자바 클라이언트 라이브러리를 사용하여 API와 상호작용하는 예를 제공합니다. 클라이언트 라이브러리 설정에 대한 도움말은 Google 데이터 자바 클라이언트 라이브러리 시작하기를 참조하세요. 자바 클라이언트 라이브러리에서 기존 Sites API와 상호작용하는 데 사용하는 기본 프로토콜에 대해 자세히 알아보려면 프로토콜 가이드를 참고하세요.

대상

이 문서는 Google 데이터 자바 클라이언트 라이브러리를 사용하여 Google Sites와 상호작용하는 클라이언트 애플리케이션을 작성하려는 개발자를 대상으로 합니다.

시작하기

Google Sites는 인증을 위해 Google 계정 또는 G Suite 계정을 사용합니다. 계정이 이미 있다면 별도의 조치를 취할 필요가 없습니다. 또는 새 계정을 만들 수 있습니다.

라이브러리 설치

클라이언트 라이브러리 설정 및 설치에 대한 도움말은 Google 데이터 자바 클라이언트 라이브러리 시작하기를 참조하세요. Eclipse를 사용하는 경우 이 도움말에서는 Google Data API Eclipse 플러그인을 사용하여 프로젝트를 설정하는 방법도 설명합니다. 시작하는 데 필요한 사항은 다음과 같습니다.

  1. 자바 1.5 이상 설치
  2. 클라이언트 라이브러리 다운로드 (최신 버전의 gdata-src.java.zip)
  3. 종속 항목 목록 다운로드
  4. 샘플 애플리케이션 (최신 버전의 gdata-samples.java.zip)을 다운로드합니다.

.jar를 설치한 후에는 프로젝트에 다음을 포함해야 합니다.

  1. java/lib/gdata-sites-2.0.jar - 버전 2.0은 기존 Sites API 버전 1.4용입니다.
  2. java/lib/gdata-core-1.0.jar
  3. java/lib/gdata-client-1.0.jar
  4. java/lib/gdata-spreadsheet-3.0.jar (목록 페이지 / 목록 항목으로 작업하는 경우)

또한 종속 항목 jar (gdata-media-1.0.jar, mail.jar, google-collect....jar)도 포함해야 합니다.

샘플 애플리케이션 실행

정상적으로 작동하는 샘플 애플리케이션은 gdata-samples.java.zip 다운로드의 /java/sample/sites 하위 디렉터리에 있습니다. 이 소스는 소스 탭에서 액세스할 수 있는 SVN 저장소의 /trunk/java/sample/sites/에도 있습니다. SitesDemo.java를 통해 사용자는 기존 Sites API를 사용하는 방법을 보여주는 여러 작업을 실행할 수 있습니다.

참고로 샘플을 실행하려면 java/sample/util/lib/sample-util.jar을 포함해야 합니다.

자체 프로젝트 시작

: Eclipse 플러그인을 빠르게 설정하려면 Google 데이터 API로 Eclipse 사용하기 도움말을 참고하세요.

애플리케이션의 필요에 따라 여러 가져오기가 필요합니다. 다음 가져오기로 시작하는 것이 좋습니다.

import com.google.gdata.client.*;
import com.google.gdata.client.sites.*;
import com.google.gdata.data.*;
import com.google.gdata.data.acl.*;
import com.google.gdata.data.media.*;
import com.google.gdata.data.sites.*;
import com.google.gdata.data.spreadsheet.*;  // If working with listpages / listitems
import com.google.gdata.util.*;

다음으로 기존 Sites API에 대한 클라이언트 연결을 나타내는 SitesService 객체도 설정해야 합니다.

SitesService client = new SitesService("yourCo-yourAppName-v1");

applicationName 인수는 company-applicationname-version 형식을 따라야 합니다. 이 매개변수는 로깅 목적으로 사용됩니다.

참고: 이 가이드의 나머지 부분에서는 client 변수에 SitesService를 만들었다고 가정합니다.

기존 Sites API 인증

자바 클라이언트 라이브러리는 공개 또는 비공개 피드 작업에 사용할 수 있습니다. Sites Data API는 Sites 권한과 수행하려는 작업에 따라 비공개 및 공개 피드에 대한 액세스를 제공합니다. 예를 들어 공개 사이트의 콘텐츠 피드를 읽을 수는 있지만 업데이트하지 못할 수 있습니다. 이러한 경우 인증된 클라이언트가 필요합니다. 이는 ClientLogin 사용자 이름/비밀번호 인증, AuthSub 또는 OAuth를 통해 수행할 수 있습니다.

AuthSub, OAuth, ClientLogin에 대한 자세한 내용은 Google 데이터 API 인증 개요를 참조하세요.

도움말: API는 SSL (HTTPS)을 지원합니다. AuthSub/OAuth를 사용하는 경우 SSL을 통해 피드를 요청하려면 https://sites.google.com/feeds/의 범위를 지정해야 합니다. 또한 G Suite 도메인의 경우 관리 제어판의 'SSL 필요' 설정이 API에 적용됩니다. client.useSsl();를 호출하여 모든 API 요청이 HTTPS를 통해 진행되도록 할 수 있습니다.

웹 애플리케이션용 AuthSub

Google 계정에 사용자를 인증해야 하는 클라이언트 애플리케이션에서는 웹 애플리케이션용 AuthSub 인증을 사용해야 합니다. 운영자는 Google Sites 사용자의 사용자 이름과 비밀번호에 액세스할 필요가 없으며 AuthSub 토큰만 있으면 됩니다.

AuthSub를 웹 애플리케이션에 통합하는 방법 보기

일회용 토큰 요청

사용자가 애플리케이션을 처음 방문할 때 인증해야 합니다. 일반적으로 개발자는 사용자를 AuthSub 승인 페이지로 안내하는 텍스트와 링크를 출력하여 사용자를 인증하고 문서에 대한 액세스를 요청합니다. Google 데이터 자바 클라이언트 라이브러리는 이 URL을 생성하는 함수를 제공합니다. 아래 코드는 AuthSubRequest 페이지로 연결되는 링크를 설정합니다.

import com.google.gdata.client.*;

String nextUrl = "http://www.example.com/welcome.jsp";
String scope = "https://sites.google.com/feeds/";
boolean secure = true;
boolean session = true;
String authSubUrl = AuthSubUtil.getRequestUrl(nextUrl, scope, secure, session);

G Suite 호스팅 도메인의 사용자를 인증하려면 다음 단계를 따르세요.

import com.google.gdata.client.*;

String hostedDomain = "example.com";
String nextUrl = "http://www.example.com/welcome.jsp";
String scope = "https://sites.google.com/feeds/";  // SSL is also supported
boolean secure = true;
boolean session = true;
String authSubUrl = AuthSubUtil.getRequestUrl(hostedDomain, nextUrl, scope, secure, session);

getRequestUrl() 메서드는 여러 매개변수를 사용합니다 (AuthSubRequest 핸들러에서 사용하는 쿼리 매개변수에 해당).

  • 다음 URL — 사용자가 계정에 로그인하고 액세스 권한을 부여한 후 Google에서 리디렉션하는 URL입니다. 위 예에서는 http://www.example.com/welcome.jsp입니다.
  • 범위 — 위 예에서 https://sites.google.com/feeds/
  • 토큰이 등록 모드에서 사용될지 여부를 나타내는 불리언. 위 예에서는 false
  • 토큰을 나중에 세션 토큰으로 교환할지 여부를 나타내는 두 번째 불리언. 위 예의 경우 true

세션 토큰으로 업그레이드

Google Data API 클라이언트 라이브러리에서 AuthSub 사용을 참조하세요.

세션 토큰 정보 가져오기

Google Data API 클라이언트 라이브러리에서 AuthSub 사용을 참조하세요.

세션 토큰 취소

Google Data API 클라이언트 라이브러리에서 AuthSub 사용을 참조하세요.

웹 또는 설치/모바일 애플리케이션용 OAuth

OAuth는 AuthSub의 대안으로 사용할 수 있으며 웹 애플리케이션용입니다. OAuth는 모든 데이터 요청이 디지털 방식으로 서명되어야 하고 도메인을 등록해야 한다는 점에서 AuthSub의 보안 및 등록 모드를 사용하는 것과 유사합니다.

설치된 애플리케이션에 OAuth를 통합하는 방법 안내 보기

요청 토큰 가져오기

Google Data API 클라이언트 라이브러리에서 OAuth 사용을 참조하세요.

요청 토큰 승인

Google Data API 클라이언트 라이브러리에서 OAuth 사용을 참조하세요.

액세스 토큰으로 업그레이드

Google Data API 클라이언트 라이브러리에서 OAuth 사용을 참조하세요.

설치/모바일 애플리케이션용 ClientLogin

ClientLogin은 사용자를 Google 계정에 인증해야 하는 설치되었거나 모바일 애플리케이션에서 사용해야 합니다. 처음 실행하면 애플리케이션이 사용자에게 사용자 이름/비밀번호를 입력하라는 메시지를 표시합니다. 후속 요청에서는 인증 토큰이 참조됩니다.

설치된 애플리케이션에 ClientLogin을 통합하는 방법에 대한 안내 보기

ClientLogin을 사용하려면 GoogleService에서 상속되는 SitesService 객체의 setUserCredentials() 메서드를 호출합니다. 클라이언트를 대신하여 요청을 수행하는 사용자의 이메일 주소와 비밀번호를 지정합니다. 예를 들면 다음과 같습니다.

SitesService client = new SitesService("yourCo-yourAppName-v1");
client.setUserCredentials("example@gmail.com", "pa$$word");

도움말: 애플리케이션에서 처음으로 사용자를 성공적으로 인증하면 나중에 사용할 수 있도록 데이터베이스에 인증 토큰을 저장하세요. 애플리케이션을 실행할 때마다 사용자에게 비밀번호를 묻는 메시지를 표시할 필요가 없습니다. 자세한 내용은 인증 토큰 리콜을 참조하세요.

자바 애플리케이션에서 ClientLogin을 사용하는 방법에 대한 자세한 내용은 Google Data API 클라이언트 라이브러리에 ClientLogin 사용을 참조하세요.

맨 위로

사이트 피드

사이트 피드는 사용자가 소유하거나 보기 권한이 있는 Google Sites를 나열하는 데 사용할 수 있습니다. 기존 사이트의 이름을 수정하는 데도 사용할 수 있습니다. G Suite 도메인의 경우 전체 사이트를 만들거나 복사하는 데 사용할 수도 있습니다.

사이트 나열

사이트 피드를 쿼리하려면 다음과 같이 사이트 피드 URL에 HTTP GET를 전송합니다.

https://sites.google.com/feeds/site/site/

다음과 같이 Java 클라이언트에서 SiteFeedSiteEntry 클래스를 사용하여 사이트 피드를 작업할 수 있습니다.

public String getSiteFeedUrl() {
  String domain = "site";  // OR if the Site is hosted on G Suite, your domain (e.g. example.com)
  return "https://sites.google.com/feeds/site/" + domain + "/";
}

public void getSiteFeed() throws IOException, ServiceException {
  SiteFeed siteFeed = client.getFeed(new URL(getSiteFeedUrl()), SiteFeed.class);
  for (SiteEntry entry : siteFeed.getEntries()){
    System.out.println("title: " + entry.getTitle().getPlainText());
    System.out.println("site name: " + entry.getSiteName().getValue());
    System.out.println("theme: " + entry.getTheme().getValue());
    System.out.println("");
  }
}

위의 스니펫은 사이트의 제목, 사이트 이름, 사이트의 테마를 출력합니다. 피드의 추가 속성에 액세스하는 데 다른 getter를 사용할 수 있습니다.

새 사이트 만들기

참고: 이 기능은 G Suite 도메인에서만 사용할 수 있습니다.

SiteEntry를 만들고 사이트 피드에서 클라이언트의 insert() 메서드를 호출하여 새 사이트를 프로비저닝할 수 있습니다.

이 예에서는 테마가 '슬레이트' (선택사항)인 새 사이트를 만들고 사이트 이름 (필수)과 설명 (선택사항)을 제공합니다.

public String getSiteFeedUrl() {
  String domain = "example.com";
  return "https://sites.google.com/feeds/site/" + domain + "/";
}

public SiteEntry createSite(String title, String summary, String theme, String tag)
    throws MalformedURLException, IOException, ServiceException {
  SiteEntry entry = new SiteEntry();
  entry.setTitle(new PlainTextConstruct(title));
  entry.setSummary(new PlainTextConstruct(summary));

  Theme tt = new Theme();
  tt.setValue(theme);
  entry.setTheme(tt);

  entry.getCategories().add(new Category(TagCategory.Scheme.TAG, tag, null));

  return client.insert(new URL(getSiteFeedUrl()), entry);
}

SiteEntry newSiteEntry = createSite("My Site Title", "summary for site", "slate", "tag");

위의 요청은 G Suite 도메인 example.com 아래에 새 사이트를 만듭니다. 따라서 사이트 URL은 https://sites.google.com/a/example.com/my-site-title이 됩니다.

사이트가 성공적으로 만들어지면 서버는 SiteEntry 객체를 통해 응답하며 이 객체는 서버에서 추가한 요소(사이트 링크, 사이트의 acl 피드 링크, 사이트 이름, 제목, 요약 등)로 채워집니다.

사이트 복사

참고: 이 기능은 G Suite 도메인에서만 사용할 수 있습니다.

사이트 복사는 새 사이트를 만드는 것과 유사합니다. 차이점은 복제할 사이트의 자체 링크가 포함된 새 SiteEntry에 링크를 설정해야 한다는 것입니다. 다음은 새 사이트 만들기 섹션에서 만든 사이트를 복제하는 예입니다.

public SiteEntry copySite(String title, String summary, String sourceHref)
    throws MalformedURLException, IOException, ServiceException {
  SiteEntry entry = new SiteEntry();
  entry.setTitle(new PlainTextConstruct(title));
  entry.setSummary(new PlainTextConstruct(summary));
  entry.addLink(SitesLink.Rel.SOURCE, Link.Type.ATOM, sourceHref);

  return client.insert(new URL(getSiteFeedUrl()), entry);
}

String sourceHref = newSiteEntry.getLink(SitesLink.Rel.SOURCE, Link.Type.ATOM).getHref();
SiteEntry myTwin = copySite("Duplicate Site", "A copy", sourceHref);

중요사항:

  • 인증된 사용자가 소유한 사이트 및 사이트 템플릿만 복사할 수 있습니다.
  • 사이트 템플릿도 복사할 수 있습니다. Google Sites 설정 페이지에서 '이 사이트를 템플릿으로 게시' 설정이 선택된 경우 사이트는 템플릿입니다.
  • 내가 원본 사이트에 소유자로 표시될 때까지 다른 도메인에서 사이트를 복사할 수 있습니다.

사이트의 메타데이터 업데이트

사이트 이름을 바꾸거나 테마, 카테고리 태그 또는 요약을 변경하려면 먼저 해당 사이트가 포함된 SiteEntry를 가져오고 하나 이상의 속성을 수정한 다음 SiteEntryupdate() 메서드를 호출해야 합니다. 이 예에서는 이전 사이트의 테마를 수정하고 사이트 이름을 바꿉니다.

myTwin.setTitle(new PlainTextConstruct("better-title"));

Theme theme = myTwin.getTheme();
theme.setValue('iceberg');
myTwin.setTheme(theme);

myTwin.getCategories().add(new Category(TagCategory.Scheme.TAG, "newTag", null));

SiteEntry updatedSiteEntry = myTwin.update();

System.out.println(updatedSiteEntry.getTitle().getPlainText();

웹 주소 매핑

Sites 사용자는 웹 주소 매핑을 통해 자신의 도메인을 Google Sites로 만든 사이트에 매핑할 수 있습니다. 예를 들어 http://sites.google.com/a/domain.com/mysite 대신 http://www.mydomainsite.com를 사용할 수 있습니다. 사이트가 호스팅되는 위치에 따라 사이트의 웹 주소 매핑을 수동으로 수정할 수 있습니다. 자세한 내용은 고객센터 도움말을 참고하세요.

사이트의 웹 주소 매핑 가져오기

사이트의 웹 주소 매핑을 반환하려면 with-mappings=true 매개변수를 사용하여 사이트 항목/피드를 가져오세요.

SiteQuery query = new SiteQuery(new URL("https://sites.google.com/feeds/site/siteName"));
query.setWithMappings(true);

SiteFeed feed = service.getFeed(query, SiteFeed.class);
for (SiteEntry entry : feed.getEntries()) {
  System.out.println("Mappings for '" + entry.getSiteName().getValue() + "':");
  for (Link link : entry.getWebAddressMappingLinks()) {
    System.out.println("  " + link.getHref());
  }
}

기존 매핑은 rel='webAddressMapping'을 포함하는 link로 표시됩니다. 예를 들어 위 예에는 http://sites.google.com/site/myOtherTestSite 사이트를 가리키는 webAddressMapping가 3개 있습니다.

웹 주소 매핑 수정

참고: 모든 GET/POST/PUT 작업은 웹 주소 매핑 작업 시 with-mappings=true 매개변수를 지정해야 합니다. 매개변수가 없으면 webAddressMapping이 사이트 항목 (GET)에 반환되지 않거나 항목에서 매핑을 업데이트/삭제 (PUT)할 때 고려되지 않습니다.

매핑을 추가, 업데이트 또는 삭제하려면 새 사이트를 만들거나 사이트의 메타데이터를 업데이트할 때 이러한 링크를 지정, 변경 또는 삭제하면 됩니다. with-mappings=true 매개변수가 사이트 피드 URI에 포함되어야 합니다. 참고: 주소 매핑을 업데이트하려면 사이트 관리자여야 하며, G Suite에서 호스팅되는 사이트의 경우 도메인 관리자여야 합니다.

예를 들어 아래 요청은 http://www.mysitemapping.com 매핑을 http://www.my-new-sitemapping.com로 업데이트하고 항목에서 링크를 삭제하여 http://www.mysitemapping2.com를 삭제합니다.

SiteEntry entry = client.getEntry(new URL("https://sites.google.com/feeds/site/site/siteName?with-mappings=true"), SiteEntry.class);

// Modify mappings (remove all mappings, add some of them again, add modified mappings)
entry.removeLinks(SitesLink.Rel.WEBADDRESSMAPPING, Link.Type.HTML);
entry.addLink(SitesLink.Rel.WEBADDRESSMAPPING, Link.Type.HTML, "http://www.my-new-sitemapping.com");

// Update the entry with the mappings.
entry.update();

사이트를 만들거나 복사할 때 웹 주소 매핑을 지정할 수도 있습니다.

맨 위로

활동 피드

활동 피드를 가져와 사이트의 최근 활동 (변경사항)을 가져올 수 있습니다. 활동 피드의 각 항목에는 사이트의 변경사항에 관한 정보가 포함됩니다.

활동 피드를 쿼리하려면 활동 피드 URL에 HTTP GET를 전송합니다.

https://sites.google.com/feeds/activity/site/siteName

자바 클라이언트에서 ActivityFeed 클래스를 사용하여 ActivityEntry 객체를 반환합니다.

public String buildActivityFeedUrl() {
  String domain = "site";  // OR if the Site is hosted on G Suite, your domain (e.g. example.com)
  String siteName = "mySite";
  return "https://sites.google.com/feeds/activity/" + domain + "/" + siteName + "/";
}

public void getActivityFeed() throws IOException, ServiceException {
  ActivityFeed activityFeed = client.getFeed(new URL(buildActivityFeedUrl()), ActivityFeed.class);
  for (BaseActivityEntry<?> entry : activityFeed.getEntries()){
    System.out.println(entry.getSummary().getPlainText());
    System.out.println(" revisions link: " + entry.getRevisionLink().getHref());
  }
}

참고: 이 피드에 액세스하려면 사이트의 공동작업자 또는 소유자여야 합니다. 클라이언트는 AuthSub, OAuth 또는 ClientLogin 토큰을 사용하여 인증해야 합니다. Sites 서비스에 인증을 참고하세요.

맨 위로

버전 피드

콘텐츠 항목의 업데이트 기록을 가져오려면 항목의 버전 링크에 HTTP GET를 전송합니다.

https://sites.google.com/feeds/revision/site/siteName/CONTENT_ENTRY_ID

이 예에서는 콘텐츠 피드를 쿼리한 다음 첫 번째 콘텐츠 항목의 버전 피드를 가져옵니다.

ContentFeed contentFeed = client.getFeed(new URL(buildContentFeedUrl()), ContentFeed.class);
URL revisionFeedUrl = new URL(contentFeed.getEntries().get(0).getRevisionLink().getHref()); // use first entry

public void getRevisionFeed(String revisionFeedUrl) throws IOException, ServiceException {
  RevisionFeed revisionFeed = client.getFeed(revisionFeedUrl, RevisionFeed.class);
  for (BaseContentEntry<?> entry : revisionFeed.getEntries()){
    System.out.println(entry.getTitle().getPlainText());
    System.out.println(" updated: " + entry.getUpdated().toUiString() + " by " +
        entry.getAuthors().get(0).getEmail());
    System.out.println(" revision #: " + entry.getRevision().getValue());
  }
}

참고: 사이트의 공동작업자 또는 소유자인 경우에만 이 피드에 액세스할 수 있습니다. 클라이언트는 AuthSub, OAuth 또는 ClientLogin 토큰을 사용하여 인증해야 합니다. Sites 서비스에 인증을 참고하세요.

맨 위로

콘텐츠 피드

콘텐츠 피드 가져오기

콘텐츠 피드는 사이트의 최신 콘텐츠를 나열합니다. HTTP GET를 콘텐츠 피드 URL에 전송하여 액세스할 수 있습니다.

https://sites.google.com/feeds/content/site/siteName
피드 매개변수설명
site'site' 또는 G Suite 호스팅 도메인의 도메인 (예: example.com)
siteName사이트의 웹 공간 이름으로 사이트의 URL에서 찾을 수 있습니다 (예: mySite).

콘텐츠 피드를 가져오는 예:

public String buildContentFeedUrl() {
  String domain = "site";  // OR if the Site is hosted on G Suite, your domain (e.g. example.com)
  String siteName = "mySite";
  return "https://sites.google.com/feeds/content/" + domain + "/" + siteName + "/";
}

ContentFeed contentFeed = client.getFeed(new URL(buildContentFeedUrl()), ContentFeed.class);

결과로 도출되는 contentFeed는 서버의 응답을 포함하는 ContentFeed 객체입니다. contentFeed의 각 항목은 사용자 사이트 내의 다른 페이지 또는 항목을 나타냅니다. ContentFeed에는 모두 BaseContentEntry에서 상속되는 다양한 유형의 객체가 포함됩니다(ListItemEntry, ListPageEntry, AttachmentEntry, WebAttachmentEntry, FileCabinetPageEntry, AnnouncementsPageEntry, AnnouncementEntry, WebPageEntry, CommentEntry).

다음은 ContentFeed에 있는 다양한 유형의 항목을 나열하는 예입니다. 각 항목 유형에는 서로 다른 속성이 포함되지만 모든 항목이 여기에 출력되지는 않습니다.

public String getContentBlob(BaseContentEntry<?> entry) {
 return ((XhtmlTextConstruct) entry.getTextContent().getContent()).getXhtml().getBlob();
}

// Extracts an entry's numeric ID.
private String getEntryId(String selfLink) {
  return selfLink.substring(selfLink.lastIndexOf("/") + 1);
}

public void printContentEntries(ContentFeed contentFeed) {
  System.out.println("Listing all WebPageEntry:");
  for (WebPageEntry entry : contentFeed.getEntries(WebPageEntry.class)) {
    System.out.println(" title: " + entry.getTitle().getPlainText());
    System.out.println(" id: " + getEntryId(entry));
    if (entry.getParentLink() != null) {
      System.out.println(" parent id: " + getEntryId(entry.getParentLink().getHref()));
    }
    System.out.println(" author: " + entry.getAuthors().get(0).getEmail());
    System.out.println(" content: " + getContentBlob(entry));
  }

  System.out.println("Listing all ListPageEntry:");
  for (ListPageEntry entry : contentFeed.getEntries(ListPageEntry.class)) {
    System.out.println(" title: " + entry.getTitle().getPlainText());
    System.out.println(" id: " + getEntryId(entry));
    for (Column col : entry.getData().getColumns()) {
      System.out.print(" [" + col.getIndex() + "] " + col.getName() + "\t");
    }
  }

  for (ListItemEntry entry : contentFeed.getEntries(ListItemEntry.class)) {
    for (Field field : entry.getFields()) {
      System.out.print(" [" + field.getIndex() + "] " + field.getValue() + "\t");
    }
    System.out.println("\n");
  }

  System.out.println("Listing all FileCabinetPageEntry:");
  for (FileCabinetPageEntry entry : contentFeed.getEntries(FileCabinetPageEntry.class)) {
    System.out.println(" title: " + entry.getTitle().getPlainText());
    System.out.println(" id: " + getEntryId(entry));
    System.out.println(" content: " + getContentBlob(entry));
  }

  System.out.println("Listing all CommentEntry:");
  for (CommentEntry entry : contentFeed.getEntries(CommentEntry.class)) {
    System.out.println(" in-reply-to: " + entry.getInReplyTo().toString());
    System.out.println(" content: " + getContentBlob(entry));
  }

  System.out.println("Listing all AnnouncementsPageEntry:");
  for (AnnouncementsPageEntry entry : contentFeed.getEntries(AnnouncementsPageEntry.class)) {
    System.out.println(" title: " + entry.getTitle().getPlainText());
    System.out.println(" id: " + getEntryId(entry));
    System.out.println(" content: " + getContentBlob(entry));
  }

  System.out.println("Listing all AnnouncementEntry:");
  for (AnnouncementEntry entry : contentFeed.getEntries(AnnouncementEntry.class)) {
    System.out.println(" title: " + entry.getTitle().getPlainText());
    System.out.println(" id: " + getEntryId(entry));
    if (entry.getParentLink() != null) {
      System.out.println(" parent id: " + getEntryId(entry.getParentLink().getHref()));
    }
    System.out.println(" draft?: " + entry.isDraft());
    System.out.println(" content: " + getContentBlob(entry));
  }

  System.out.println("Listing all AttachmentEntry:");
  for (AttachmentEntry entry : contentFeed.getEntries(AttachmentEntry.class)) {
    System.out.println(" title: " + entry.getTitle().getPlainText());
    System.out.println(" id: " + getEntryId(entry));
    if (entry.getParentLink() != null) {
      System.out.println(" parent id: " + getEntryId(entry.getParentLink().getHref()));
    }
    if (entry.getSummary() != null) {
      System.out.println(" description: " + entry.getSummary().getPlainText());
    }
    System.out.println(" revision: " + entry.getRevision().getValue());
    MediaContent content = (MediaContent) entry.getContent();
    System.out.println(" src: " + content.getUri());
    System.out.println(" content type: " + content.getMimeType().getMediaType());
  }

  System.out.println("Listing all WebAttachmentEntry:");
  for (WebAttachmentEntry entry : contentFeed.getEntries(WebAttachmentEntry.class)) {
    System.out.println(" title: " + entry.getTitle().getPlainText());
    System.out.println(" id: " + getEntryId(entry));
    if (entry.getParentLink() != null) {
      System.out.println(" parent id: " + getEntryId(entry.getParentLink().getHref()));
    }
    if (entry.getSummary() != null) {
      System.out.println(" description: " + entry.getSummary().getPlainText());
    }
    System.out.println(" src: " + ((MediaContent) entry.getContent()).getUri());
  }
}

참고: 이 피드는 사이트의 공유 권한에 따라 인증이 필요할 수도 있고 필요하지 않을 수도 있습니다. 비공개 사이트인 경우 클라이언트는 AuthSub, OAuth 또는 ClientLogin 토큰을 사용하여 인증해야 합니다. Sites 서비스에 인증을 참고하세요.

콘텐츠 피드 쿼리 예

일부 표준 Google Data API 쿼리 매개변수와 기존 Sites API 전용의 매개변수를 사용하여 콘텐츠 피드를 검색할 수 있습니다. 자세한 내용과 지원되는 매개변수의 전체 목록은 참조 가이드를 확인하세요.

참고: 이 섹션의 예에서는 콘텐츠 피드 검색buildContentFeedUrl() 메서드를 사용합니다.

특정 항목 종류 검색

특정 유형의 항목만 가져오려면 kind 매개변수를 사용하세요. 이 예시에서는 attachment 항목만 반환합니다.

ContentQuery query = new ContentQuery(new URL(buildContentFeedUrl()));
query.setKind("webpage");
ContentFeed contentFeed = client.getFeed(query, ContentFeed.class);
for (AttachmentEntry entry : contentFeed.getEntries(AttachmentEntry.class)) {
  System.out.println(entry.getTitle().getPlainText());
}

항목 유형을 두 개 이상 반환하려면 각 kind을 ','로 구분하세요. 이 예시에서는 filecabinetlistpage 항목을 반환합니다.

URL url = new URL(buildContentFeedUrl() + "?kind=filecabinet,listpage");
ContentFeed contentFeed = client.getFeed(url, ContentFeed.class);
for (FileCabinetPageEntry entry : contentFeed.getEntries(FileCabinetPageEntry.class)) {
  System.out.println(" title: " + entry.getTitle().getPlainText());
}
for (ListPageEntry entry : contentFeed.getEntries(ListPageEntry.class)) {
  System.out.println(" title: " + entry.getTitle().getPlainText());
}

경로로 페이지 가져오기

Google 사이트 내 페이지의 상대 경로를 알고 있는 경우 path 매개변수를 사용하여 특정 페이지를 가져올 수 있습니다. 이 예에서는 http://sites.google.com/site/siteName/path/to/the/page에 있는 페이지를 반환합니다.

ContentQuery query = new ContentQuery(new URL(buildContentFeedUrl()));
query.setPath("/path/to/the/page");
ContentFeed contentFeed = client.getFeed(query, ContentFeed.class);
for (BaseContentEntry<?> entry : contentFeed.getEntries()) {
  System.out.println(" title: " + entry.getTitle().getPlainText());
}

상위 페이지에 있는 모든 항목 검색

페이지의 콘텐츠 항목 ID (예: 아래 예에서는 '1234567890')를 알고 있으면 parent 매개변수를 사용하여 모든 하위 항목 (있는 경우)을 가져올 수 있습니다.

ContentQuery query = new ContentQuery(new URL(buildContentFeedUrl()));
query.setParent("1234567890");
ContentFeed contentFeed = client.getFeed(query, ContentFeed.class);

추가 매개변수에 대해서는 참조 가이드를 확인하세요.

맨 위로



콘텐츠 제작

참고: 사이트 콘텐츠를 만들기 전에 클라이언트에서 사이트를 설정해야 합니다.
client.site = "siteName";

새 콘텐츠 (웹페이지, 목록 페이지, 자료실 페이지, 공지사항 페이지 등)는 콘텐츠 피드에 HTTP POST를 전송하여 만들 수 있습니다.

https://sites.google.com/feeds/content/site/siteName

지원 노드 유형 목록은 참조 가이드kind 매개변수를 참조하세요.

새 항목 / 페이지 만들기

이 예에서는 사이트의 최상위 수준 아래에 새 webpage를 만들고 페이지 본문을 위한 일부 XHTML을 포함하며 제목 제목을 '새 웹페이지 제목'으로 설정합니다.

private void setContentBlob(BaseContentEntry<?> entry, String pageContent) {
  XmlBlob xml = new XmlBlob();
  xml.setBlob(pageContent);
  entry.setContent(new XhtmlTextConstruct(xml));
}

public WebPageEntry createWebPage(String title, String content)
    throws MalformedURLException, IOException, ServiceException {
  WebPageEntry entry = new WebPageEntry();
  entry.setTitle(new PlainTextConstruct(title));

  setContentBlob(entry, content); // Entry's HTML content

  return client.insert(new URL(buildContentFeedUrl()), entry);
}

WebPageEntry createdEntry = createWebPage("New Webpage Title", "<b>HTML content</b>");
System.out.println("Created! View at " + createdEntry.getHtmlLink().getHref());

요청이 성공하면 createdEntry에 서버에 생성된 항목의 사본이 포함됩니다.

맞춤 URL 경로에 항목/페이지 만들기

기본적으로 이전 예시는 URL http://sites.google.com/site/siteName/new-webpage-title로 생성되고 페이지 제목은 '새 웹페이지 제목'입니다. 즉, URL의 <atom:title>new-webpage-title로 정규화됩니다. 페이지의 URL 경로를 맞춤설정하려면 <sites:pageName> 요소를 설정하면 됩니다.

이 예시에서는 제목이 'File Storage'인 새 filecabinet 페이지를 만들지만 <sites:pageName> 요소를 지정하여 URL http://sites.google.com/site/siteName/files(http://sites.google.com/site/siteName/file-storage 대신)에 페이지를 만듭니다.

public FileCabinetPageEntry createFileCabinetPage(String title, String content, String customPageName)
    throws MalformedURLException, IOException, ServiceException {
  FileCabinetPageEntry entry = new FileCabinetPageEntry();
  entry.setTitle(new PlainTextConstruct(title));

  setContentBlob(entry, content); // Entry's HTML content

  entry.setPageName(new PageName(customPageName)); // Upload to a custom page path

  return client.insert(new URL(buildContentFeedUrl()), entry);
}

FileCabinetPageEntry createdEntry = createFileCabinetPage("File Storage", "<b>HTML content</b>", "files");
System.out.println("Created! View at " + createdEntry.getHtmlLink().getHref());

서버는 페이지 URL 경로의 이름을 지정하기 위해 다음 우선순위 규칙을 사용합니다.

  1. <sites:pageName>(있는 경우) a-z, A-Z, 0-9, -, _을 충족해야 합니다.
  2. <atom:title>이며 pageName이 없는 경우 null이 아니어야 합니다. 정규화는 공백을 잘라내고 '-'로 접고 a-z, A-Z, 0-9, -, _와 일치하지 않는 문자를 삭제하는 것입니다.

하위 페이지 만들기

상위 페이지 아래에 하위 페이지 (하위 페이지)를 만들려면 항목에서 상위 링크를 설정해야 합니다. 상위 노드의 자체 링크에 대한 링크의 href 속성.

public AnnouncementEntry postAnnouncement(String title, String content, AnnouncementsPageEntry parentPage)
    throws MalformedURLException, IOException, ServiceException {
  AnnouncementEntry entry = new AnnouncementEntry();
  entry.setTitle(new PlainTextConstruct(title));

  setContentBlob(entry, content); // Entry's HTML content

  // Set the entry's parent link to create the announcement under that page.
  entry.addLink(SitesLink.Rel.PARENT, Link.Type.ATOM, parentPage.getSelfLink().getHref());

  return client.insert(new URL(buildContentFeedUrl()), entry);
}

ContentFeed contentFeed = client.getFeed(new URL(buildContentFeedUrl() + "?kind=announcementspage"), ContentFeed.class);

AnnouncementEntry createdEntry = postAnnouncement("Party!!", "My place, this weekend", contentFeed.getEntries().get(0));
System.out.println("New post by " + createdEntry.getAuthors().get(0).getName());

위의 예에서는 사용자의 콘텐츠 피드에서 발견된 첫 번째 공지사항 페이지에 새 announcement를 만듭니다. 공지사항 제목은 '파티!!'로, 콘텐츠는 '이번 주말 우리 장소'로 설정되어 있습니다.

페이지 템플릿

페이지 템플릿 만들기

페이지 템플릿을 만드는 과정은 새 항목/페이지 만들기하위 페이지 만들기와 동일합니다.차이점은 용어와 라벨이 각각 'http://schemas.google.com/g/2005#template' 및 '템플릿'으로 설정된 category가 추가된다는 점입니다.

이 예에서는 새 webpage 템플릿을 만듭니다.

// The template webpage entry.
WebPageEntry entry = new WebPageEntry();

// Set title and content.
entry.setTitle(new PlainTextConstruct("Page template title"));
XmlBlob xml = new XmlBlob();
xml.setBlob("Content for page template");
entry.setContent(new XhtmlTextConstruct(xml));

// Set the template category
Category TEMPLATE_CATEGORY = new Category(TemplateCategory.Scheme.LABELS,
    TemplateCategory.Term.TEMPLATE, TemplateCategory.Label.TEMPLATE);
entry.getCategories().add(TEMPLATE_CATEGORY);

// Insert the template webpage entry.
WebPageEntry createdEntry = client.insert(new URL("https://sites.google.com/feeds/content/site/siteName"), entry);

템플릿으로 페이지 만들기

페이지 템플릿을 만드는 것과 마찬가지로, 페이지 템플릿의 자체 링크를 가리키는 rel='http://schemas.google.com/sites/2008#template'과 함께 <link>를 포함하여 템플릿에서 새 페이지를 인스턴스화할 수 있습니다.

이 예에서는 새 filecabinet 템플릿을 만든 다음 이 템플릿에서 새 filecabinet 페이지를 인스턴스화합니다.

URL feedUrl = new URL("https://sites.google.com/feeds/content/site/siteName");

// 1. Create file cabinet page template
FileCabinetPageEntry inputTemplateEntry = new FileCabinetPageEntry();
inputTemplateEntry.setTitle(new PlainTextConstruct("File cabinet page template title"));
XmlBlob xml = new XmlBlob();
xml.setBlob("Content for page template");
inputTemplateEntry.setContent(new XhtmlTextConstruct(xml));

// Set the template category
Category TEMPLATE_CATEGORY = new Category(TemplateCategory.Scheme.LABELS,
    TemplateCategory.Term.TEMPLATE, TemplateCategory.Label.TEMPLATE);
inputTemplateEntry.getCategories().add(TEMPLATE_CATEGORY);

// 2. Create file cabinet page template instance
FileCabinetPageEntry templateEntry = client.insert(feedUrl, inputTemplateEntry);

// Specify link to the page template
FileCabinetPageEntry templateInstanceEntry = new FileCabinetPageEntry();
templateInstanceEntry.setTitle(new PlainTextConstruct("File cabinet template instance"));
templateInstanceEntry.addLink(new Link(SitesLink.Rel.TEMPLATE, Link.Type.ATOM, templateEntry.getSelfLink().getHref()));

FileCabinetPageEntry createdFileCabinetFromTemplate =  client.insert(feedUrl, templateInstanceEntry);

참고: 템플릿에서 <category>를 정의하고 항목에도 계속 지정해야 합니다. 또한 <content> 요소를 포함하면 서버에서 이를 거부합니다.

파일 업로드

Google 사이트 도구에서와 마찬가지로 API는 자료실 페이지 또는 상위 페이지에 첨부파일을 업로드하는 기능을 지원합니다.

상위 파일에 첨부파일을 업로드하려면 HTTP POST 요청을 콘텐츠 피드 URL로 전송합니다.

https://sites.google.com/feeds/content/site/siteName

모든 첨부파일 유형은 상위 페이지에 업로드해야 합니다. 따라서 업로드하려는 AttachmentEntry 또는 WebAttachmentEntry 객체에 상위 링크를 설정합니다. 자세한 내용은 하위 페이지 만들기를 참고하세요.

첨부파일 업로드 중

이 예에서는 사용자의 콘텐츠 피드에 있는 첫 번째 FileCabinetPageEntry에 PDF 파일을 업로드합니다. 제목이 '시작하기'이고 설명 (선택사항)인 'HR 패킷'이 포함된 연결이 생성됩니다.

MimetypesFileTypeMap mediaTypes = new MimetypesFileTypeMap();
mediaTypes.addMimeTypes("application/msword doc");
mediaTypes.addMimeTypes("application/vnd.ms-excel xls");
mediaTypes.addMimeTypes("application/pdf pdf");
mediaTypes.addMimeTypes("text/richtext rtx");
// ... See a more complete list of mime types in the SitesHelper.java

public AttachmentEntry uploadAttachment(File file, BasePageEntry<?> parentPage,
    String title, String description) throws IOException, ServiceException {
  AttachmentEntry newAttachment = new AttachmentEntry();
  newAttachment.setMediaSource(new MediaFileSource(file, mediaTypes.getContentType(file)));
  newAttachment.setTitle(new PlainTextConstruct(title));
  newAttachment.setSummary(new PlainTextConstruct(description));
  newAttachment.addLink(SitesLink.Rel.PARENT, Link.Type.ATOM, parentPage.getSelfLink().getHref());

  return client.insert(new URL(buildContentFeedUrl()), newAttachment);
}

ContentFeed contentFeed = client.getFeed(new URL(buildContentFeedUrl() + "?kind=filecabinet"), ContentFeed.class);
FileCabinetPageEntry parentPage = contentFeed.getEntries(FileCabinetPageEntry.class).get(0);

AttachmentEntry attachment = uploadAttachment(
    new File("/path/to/your/file.pdf"), parentPage, "Getting Started", "HR packet");
System.out.println("Uploaded!");

업로드가 성공하면 attachment에 생성된 첨부파일 항목의 사본이 포함됩니다.

폴더에 첨부파일 업로드

첨부파일을 FileCabinetPageEntry의 기존 폴더에 업로드하려면 'term' 속성이 폴더 이름으로 설정된 카테고리를 포함하세요. 예를 들어 uploadAttachment()에 다음 줄을 추가합니다.

newAttachment.getCategories().add(new Category("http://schemas.google.com/sites/2008#folder", "FolderName"));

웹 첨부파일

웹 첨부파일은 특별한 종류의 첨부파일입니다. 기본적으로 이는 웹에 있는 다른 파일에 대한 링크로서 파일 캐비닛 목록에 추가할 수 있습니다. 이 기능은 Google Sites UI의 'URL로 파일 추가' 업로드 방법과 유사합니다.

참고: 웹 첨부파일은 자료실에서만 만들 수 있습니다. 다른 유형의 페이지에는 업로드할 수 없습니다.

이 예에서는 사용자의 콘텐츠 피드에서 발견된 첫 번째 FileCabinetPageEntry 아래에 WebAttachmentEntry를 만듭니다. 제목과 설명 (선택사항)은 각각 'GoogleLogo'와 'nice colors'로 설정되어 있습니다.

public WebAttachmentEntry uploadWebAttachment(String contentUrl, FileCabinetPageEntry filecabinet,
    String title, String description) throws MalformedURLException, IOException, ServiceException {
  MediaContent content = new MediaContent();
  content.setUri(contentUrl);

  WebAttachmentEntry webAttachment = new WebAttachmentEntry();
  webAttachment.setTitle(new PlainTextConstruct(title));
  webAttachment.setSummary(new PlainTextConstruct(description));
  webAttachment.setContent(content);
  webAttachment.addLink(SitesLink.Rel.PARENT, Link.Type.ATOM,
      filecabinet.getSelfLink().getHref());

  return client.insert(new URL(buildContentFeedUrl()), webAttachment);
}

ContentFeed contentFeed = client.getFeed(new URL(buildContentFeedUrl() + "?kind=filecabinet"), ContentFeed.class);
FileCabinetPageEntry parentPage = contentFeed.getEntries(FileCabinetPageEntry.class).get(0);

WebAttachmentEntry webAttachment =
    uploadWebAttachment("http://www.google.com/images/logo.gif", parentPage, "Google's Logo", "nice colors");
System.out.println("Web attachment created!");

POST는 사용자의 자료실에 'http://www.google.com/images/logo.gif'의 이미지를 가리키는 링크를 만듭니다.

맨 위로



콘텐츠 업데이트

페이지의 메타데이터 또는 html 콘텐츠 업데이트

모든 BaseContentEntry 유형의 메타데이터 (제목, 페이지 이름 등) 및 페이지 콘텐츠는 항목의 update() 메서드를 사용하여 수정할 수 있습니다. 그러면 HTTP PUT 요청이 항목의 edit 링크로 전송됩니다.

다음은 ListPageEntry를 다음 변경사항으로 업데이트하는 예입니다.

  • 제목이 '업데이트된 제목'으로 수정됨
  • 페이지의 HTML 콘텐츠가 '<p>업데이트된 HTML 콘텐츠</p>'로 업데이트됩니다.
  • 목록의 첫 번째 열 제목이 '소유자'로 변경됨
ContentFeed contentFeed = client.getFeed(
    new URL(buildContentFeedUrl() + "?kind=listpage"), ContentFeed.class);
ListPageEntry listPage = contentFeed.getEntries(ListPageEntry.class).get(0); // Update first list page found

// Update title
listPage.setTitle(new PlainTextConstruct("Updated Title"));

// Update HTML content
XmlBlob xml = new XmlBlob();
xml.setBlob("<p>Updated HTML Content</p>");
listPage.setContent(new XhtmlTextConstruct(xml));

// Change first column's heading
listPage.getData().getColumns().get(0).setName("Owner");

// listPage.setPageName(new PageName("new-page-path"));  // You can also change the page's URL path

ListPageEntry updatedEntry = listPage.update();

System.out.println("ListPage updated!");

첨부파일 콘텐츠 업데이트 중

AttachmentEntry의 경우 항목의 MediaSource를 설정한 후 항목의 updateMedia(boolean) 메서드를 사용하여 콘텐츠를 업데이트할 수도 있습니다.

이 예는 기존 첨부파일의 콘텐츠를 업데이트합니다.

public AttachmentEntry updateFile(AttachmentEntry entry, File newFile)
    throws IOException, ServiceException {
  // See Uploading Attachments for the definition of mediaTypes.
  entry.setMediaSource(new MediaFileSource(newFile, mediaTypes.getContentType(newFile)));
  return entry.updateMedia(false);
}

이 예시에서는 항목의 edit-media 링크에 HTTP PUT 요청을 전송합니다. 반환된 AttachmentEntry에는 업데이트된 콘텐츠가 포함됩니다.

첨부파일 메타데이터 및 콘텐츠 업데이트

updateMedia() 메서드를 사용하여 동일한 호출에서 첨부파일의 메타데이터와 콘텐츠를 업데이트할 수 있습니다. 파일 콘텐츠만 업데이트하거나 메타데이터만 업데이트할 수 있거나 둘 다 업데이트할 수 있는 경우

이 예에서는 첨부파일의 제목을 '새 제목'으로 변경하고 설명을 업데이트하고 파일 콘텐츠를 새 .zip 파일로 바꿉니다. 요청에 새 파일 콘텐츠가 포함되어 있으므로 AttachmentEntryupdateMedia()가 사용됩니다.

public AttachmentEntry updateAttachment(AttachmentEntry entry, File newFile, String newTitle, String newDescription)
    throws IOException, ServiceException  {
  // See Uploading Attachments for the definition of mediaTypes.
  entry.setMediaSource(new MediaFileSource(newFile, mediaTypes.getContentType(newFile)));
  entry.setTitle(new PlainTextConstruct(newTitle));
  entry.setSummary(new PlainTextConstruct(newDescription));

  return entry.updateMedia(true);
}

ContentFeed contentFeed = client.getFeed(
    new URL(buildContentFeedUrl() + "?kind=attachment&max-results=1"), ContentFeed.class);
AttachmentEntry attachment = contentFeed.getEntries(AttachmentEntry.class).get(0); // Update first attachment found

AttachmentEntry updatedAttachment = updateAttachment(attachment, new File("/path/to/file.zip"), "New Title", "better stuff");

맨 위로



콘텐츠 삭제

Google 사이트에서 페이지나 항목을 삭제하려면 먼저 콘텐츠 항목을 가져온 다음 항목의 delete()를 호출합니다.

entry.delete();

서비스 클래스의 delete() 메서드에 항목의 edit 링크와 ETag 값을 전달하여 사용할 수도 있습니다.

client.delete(entry.getEditLink().getHref(), "*"); // Note: using "*" may overwrite another client's changes.

항목이 성공적으로 삭제되면 서버에서 HTTP 200 OK로 응답합니다.

맨 위로



첨부파일 다운로드

AttachmentEntry를 다운로드하려면 HTTP GET 요청을 항목의 콘텐츠 src 링크에 전송합니다.

다음 예에서는 사용자의 콘텐츠 피드에 있는 첫 번째 AttachmentEntry를 '/path/to/save/file/' 디렉터리로 다운로드합니다.

private void downloadFile(String downloadUrl, String fullFilePath) throws IOException, ServiceException {
  System.out.println("Downloading file from: " + downloadUrl);

  MediaContent mc = new MediaContent();
  mc.setUri(downloadUrl);
  MediaSource ms = service.getMedia(mc);

  InputStream inStream = null;
  FileOutputStream outStream = null;

  try {
    inStream = ms.getInputStream();
    outStream = new FileOutputStream(fullFilePath);

    int c;
    while ((c = inStream.read()) != -1) {
      outStream.write(c);
    }
  } finally {
    if (inStream != null) {
      inStream.close();
    }
    if (outStream != null) {
      outStream.flush();
      outStream.close();
    }
  }
}

public void downloadAttachment(AttachmentEntry entry, String directory) throws IOException, ServiceException {
  String url = ((OutOfLineContent) entry.getContent()).getUri();
  downloadFile(url, directory + entry.getTitle().getPlainText()); // Use entry's title for the save filename
}

ContentFeed contentFeed = client.getFeed(
    new URL(buildContentFeedUrl() + "?kind=attachment&max-results=1"), ContentFeed.class);

downloadAttachment(contentFeed.getEntries(AttachmentEntry.class).get(0), "/path/to/save/file/");
System.out.println("Downloaded.");

맨 위로

ACL 피드

공유 권한 (ACL) 개요

ACL 피드의 각 ACL 항목은 사용자, 사용자 그룹, 도메인 또는 기본 액세스 (공개 사이트)와 같은 특정 항목의 액세스 역할을 나타냅니다. 항목은 명시적 액세스 권한이 있는 항목에만 표시됩니다. Google Sites UI 공유 화면의 '액세스 권한이 있는 사용자' 패널에 각 이메일 주소별로 항목이 하나씩 표시됩니다. 따라서 사이트에 대한 암시적 액세스 권한이 있더라도 도메인 관리자가 표시되지 않습니다.

역할

역할 요소는 항목이 가질 수 있는 액세스 수준을 나타냅니다. gAcl:role 요소에 가능한 값은 4가지입니다.

  • Reader — 뷰어입니다 (읽기 전용 액세스와 동일).
  • writer — 공동작업자 (읽기/쓰기 액세스 권한과 동일)
  • owner — 일반적으로 사이트 관리자입니다 (읽기/쓰기 액세스 권한과 동일).

범위

범위 요소는 이 액세스 수준을 가진 항목을 나타냅니다. gAcl:scope 요소에는 네 가지 가능한 유형이 있습니다.

  • user — 이메일 주소 값(예: 'user@gmail.com')
  • group — Google 그룹 이메일 주소(예: 'group@domain.com')
  • domain — G Suite 도메인 이름(예: 'domain.com')
  • default - 값이 없는 '기본' 유형의 가능한 범위는 하나만 있습니다(예: <gAcl:scope type="default">). 이 특정 범위는 공개 사이트에서 모든 사용자가 기본적으로 갖는 액세스 권한을 제어합니다.

참고: 도메인에서 gAcl:role 값을 '소유자' 액세스로 설정할 수 없으며 리더 또는 작성자만 지정할 수 있습니다.

ACL 피드 가져오기

AclFeedAclEntry 클래스는 사이트의 공유 권한을 제어하는 데 사용할 수 있으며 서비스 클래스의 getFeed() 메서드를 사용하여 가져올 수 있습니다.

다음 예에서는 지정된 사이트의 ACL 피드를 가져오고 각 AclEntry의 권한을 출력합니다.

public String getAclFeedUrl(String siteName) {
  String domain = "site";  // OR if the Site is hosted on G Suite, your domain (e.g. example.com)
  return "https://sites.google.com/feeds/acl/site/" + domain + "/" + siteName + "/";
}

public void getAclFeed(String siteName) throws IOException, ServiceException {
  AclFeed aclFeed = client.getFeed(new URL(getAclFeedUrl(siteName)), AclFeed.class);
  for (AclEntry entry : aclFeed.getEntries()) {
    System.out.println(entry.getScope().getValue() + " (" + entry.getScope().getType() + ") : " +
                       entry.getRole().getValue());
  }
}

getAclFeed('my-site-name');

SiteFeed에서 항목을 사용하는 경우 각 SiteEntry에는 ACL 피드 링크가 포함됩니다. 예를 들어 다음 스니펫은 SiteEntry의 acl 피드를 가져옵니다.

String aclLink = siteEntry.getLink(SitesAclFeedLink.Rel.ACCESS_CONTROL_LIST, Link.Type.ATOM).getHref();
AclFeed aclFeed = client.getFeed(new URL(aclLink), AclFeed.class);

사이트 공유

참고: 일부 공유 ACL은 도메인이 이러한 권한을 허용하도록 구성된 경우에만 사용할 수 있습니다 (예: G Suite 도메인의 도메인 외부에 공유가 사용 설정된 경우).

API를 사용하여 Google Sites로 만든 사이트를 공유하려면 클라이언트가 새 AclEntry를 만들어 서버에 POST해야 합니다.

다음은 사이트에서 'user@example.com'을 reader로 추가하는 예입니다.

AclRole role = new AclRole("reader");
AclScope scope = new AclScope(AclScope.Type.USER, "user@example.com");
AclEntry aclEntry = addAclRole(role, scope, entry);

public AclEntry addAclRole(AclRole role, AclScope scope, SiteEntry siteEntry)
    throws IOException, MalformedURLException, ServiceException  {
  AclEntry aclEntry = new AclEntry();
  aclEntry.setRole(role);
  aclEntry.setScope(scope);

  Link aclLink = siteEntry.getLink(SitesAclFeedLink.Rel.ACCESS_CONTROL_LIST, Link.Type.ATOM);
  return client.insert(new URL(aclLink.getHref()), aclEntry);
}

가능한 AclScopeAclRoles 값은 ACL 피드 개요 섹션을 참고하세요.

그룹 및 도메인 수준 공유

단일 사용자와 사이트를 공유할 때와 마찬가지로 Google 그룹 또는 G Suite 도메인 간에 사이트를 공유할 수 있습니다.

그룹 이메일 주소로 공유:

AclScope scope = new AclScope(AclScope.Type.GROUP, "group_name@example.com");

전체 도메인에 공유:

AclScope scope = new AclScope(AclScope.Type.DOMAIN, "example.com");

도메인 수준에서의 공유는 G Suite 도메인과 사이트가 호스팅되는 도메인에만 지원됩니다. 예를 들어 http://sites.google.com/a/domain1.com/siteA에서는 전체 사이트를 domain2.com이 아닌 domain1.com에만 공유할 수 있습니다. G Suite 도메인 (예: http://sites.google.com/site/siteB)에서 호스팅되지 않는 사이트는 도메인을 초대할 수 없습니다.

공유 권한 수정

사이트의 기존 공유 권한으로 우선 해당 AclEntry를 가져와서 권한을 원하는 대로 수정한 다음 AclEntryupdate() 메서드를 호출하여 서버의 ACL을 수정합니다.

이 예에서는 'user@example.com'을 writer (공동작업자)로 업데이트하여 사이트 공유 섹션의 이전 aclEntry 예를 수정합니다.

aclEntry.setRole(new AclRole("writer"));
AclEntry updatedAclEntry = aclEntry.update();

// Could also use the client's update method
// client.update(new URL(aclEntry.getEditLink().getHref()), aclEntry);

ETag에 대한 자세한 내용은 Google Data API 참조 가이드를 확인하세요.

공유 권한 삭제 중

공유 권한을 삭제하려면 먼저 AclEntry를 가져온 다음 delete() 메서드를 호출합니다.

aclEntry.delete();

// Could also use the client's delete method
// client.delete(new URL(aclEntry.getEditLink().getHref()), aclEntry);

ETag에 대한 자세한 내용은 Google Data API 참조 가이드를 확인하세요.

맨 위로

특별 주제

피드 또는 항목 다시 가져오기

이전에 검색한 피드나 항목을 검색하려는 경우 마지막으로 검색한 이후에 변경된 목록이나 항목만 전송하도록 서버에 지시하여 효율성을 높일 수 있습니다.

이러한 종류의 조건부 검색을 수행하기 위해 getFeed()getEntry() 메서드는 모두 If-Modified-Since 헤더에 대해 ETag 값 또는 DateTime 객체를 허용하는 추가 인수를 제공합니다. entry.getEtag()에서 항목의 ETag에 액세스할 수 있습니다.

다음 예에서는 콘텐츠 웹페이지 항목에 대한 조건부 검색을 수행합니다.

String feedUrl = "https://sites.google.com/feeds/content/site/siteName/123456789";
WebPageEntry entry = client.getEntry(new URL(feedUrl), WebPageEntry.class, "\"GVQHSARDQyp7ImBq\"");

서버는 이 요청을 수신하면 요청한 항목에 지정된 ETag와 동일한 ETag가 있는지 확인합니다. ETag가 일치하면 항목이 변경되지 않고 서버에서 HTTP 304 NotModifiedException 예외가 발생합니다.

ETag가 일치하지 않으면 마지막 요청 이후 항목이 수정된 것이므로 서버에서 항목을 반환합니다.

ETag에 대한 자세한 내용은 Google Data API 참조 가이드를 확인하세요.

맨 위로