자바 언어 가이드

중요: 이 문서는 2012년 이전에 작성되었습니다. 인증 옵션 인증 (OAuth 1.0, AuthSub 및 ClientLogin)을 위해 OAuth 1.0, AuthSub, ClientLogin 공식적으로 지원 중단됨 2012년 4월 20일부터 더 이상 사용할 수 없습니다. 최신 버전으로 되도록 빠른 시일 내에 OAuth 2.0으로 업데이트하시기 바랍니다.

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

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

잠재고객

이 문서는 Google 사이트 도구와 상호작용하는 클라이언트 애플리케이션을 작성하려는 개발자를 위해 작성되었습니다. Google 데이터 자바 클라이언트 라이브러리 사용

시작하기

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

라이브러리 설치

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

  1. Java 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 하위 디렉터리에 있습니다. 이 소스는 /trunk/java/sample/sites/에서도 볼 수 있습니다. 소스 탭에서 액세스할 수 있는 SVN 저장소에 저장됩니다. 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 인증하기

Java 클라이언트 라이브러리는 공개 또는 비공개 피드 작업에 사용할 수 있습니다. Sites Data API를 통해 비공개 및 공개 액세스가 가능 사이트 도구 권한 및 수행하려는 작업에 따라 달라집니다. 예를 들어, 업데이트할 수는 없습니다. 이는 인증된 클라이언트가 필요한 작업입니다. 이 작업은 ClientLogin 사용자 이름/비밀번호 인증, AuthSub 또는 OAuth.

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

도움말: API는 SSL (HTTPS)을 지원합니다. AuthSub/OAuth를 사용하는 경우 SSL을 통한 피드를 요청하기 위해 https://sites.google.com/feeds/의 범위를 지정해야 합니다. 또한 G Suite 도메인, 설정이 API에 적용됩니다. 모든 네트워크 연결을 client.useSsl();를 호출하여 HTTPS를 통한 API 요청

웹 애플리케이션용 AuthSub

웹 애플리케이션에 대한 AuthSub 인증은 인증 정보를 제공해야 하는 클라이언트 애플리케이션에서 Google 계정에 사용자를 인증합니다. 작업자는 Google Sites 사용자의 사용자 이름과 비밀번호에 액세스할 필요가 없으며 AuthSub 토큰은 필수 항목입니다.

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

일회용 토큰 요청

사용자가 애플리케이션을 처음 방문할 때 인증해야 합니다. 일반적으로 개발자는 사용자를 안내하는 일부 텍스트와 링크를 인쇄합니다. AuthSub 승인 페이지로 이동하여 사용자를 인증하고 문서에 대한 액세스를 요청합니다. Google 데이터 Java 클라이언트 라이브러리는 생성합니다. 아래 코드는 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 데이터 API 클라이언트 라이브러리에 OAuth 사용을 참조하세요.

요청 토큰 승인

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

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

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

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

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

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

ClientLogin을 사용하려면 로그인 setUserCredentials() 메서드에서 상속된 SitesService 객체의 메서드 GoogleService: 사용자의 이메일 주소와 비밀번호를 지정합니다. 확인할 수 있습니다. 예를 들면 다음과 같습니다.

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

도움말: 애플리케이션에서 처음으로 사용자를 인증하면 기억해 두었다가 나중에 사용할 수 있습니다 애플리케이션을 실행할 때마다 사용자에게 비밀번호를 입력하라는 메시지를 표시하지 않아도 됩니다. 자세한 내용은 인증 토큰 다시 호출을 참조하세요.

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

맨 위로

사이트 피드

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

사이트 나열

사이트 피드를 쿼리하려면 HTTP GET를 사이트 피드 URL에 보냅니다.

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://www.mydomainsite.com http://sites.google.com/a/domain.com/mysite 대신 사용할 수 있습니다. 사이트가 호스팅되는 위치에 따라 매핑 작업을 수행합니다. 자세한 내용은 고객센터 도움말을 참고하세요.

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

사이트의 웹 주소 매핑을 반환하려면 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로 표시됩니다. 예를 들어, 위의 예에서 사이트를 가리키는 3개의 webAddressMapping가 있음 http://sites.google.com/site/myOtherTestSite입니다.

웹 주소 매핑 수정

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

매핑을 추가, 업데이트 또는 삭제하려면 새 사이트를 만들 때 해당 링크를 지정, 변경 또는 삭제하면 됩니다. 사이트의 메타데이터 업데이트 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();

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

맨 위로

활동 피드

활동 피드를 가져오면 사이트의 최근 활동 (변경사항)을 가져올 수 있습니다. 목록의 각 항목은 활동 피드에는 사이트의 변경사항에 대한 정보가 들어 있습니다.

활동 피드를 쿼리하려면 HTTP GET를 활동 피드 URL에 보냅니다.

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

Java 클라이언트에서 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 토큰을 사용하여 인증해야 합니다. 사이트 도구 서비스에 인증하기를 참고하세요.

맨 위로

버전 피드

콘텐츠 항목의 업데이트 기록을 가져오려면 항목의 버전 링크에 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 토큰을 사용하여 인증해야 합니다. 사이트 도구 서비스에 인증하기를 참고하세요.

맨 위로

콘텐츠 피드

콘텐츠 피드 가져오기

콘텐츠 피드에는 사이트의 최신 콘텐츠가 나열됩니다. 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 토큰을 사용하여 인증해야 합니다. 자세한 내용은 사이트 도구 서비스에 인증

콘텐츠 피드 쿼리 예

표준 Google 데이터 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을 ','로 구분합니다. 이 예시에서는 filecabinet를 반환하고 항목 listpage개:

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 페이지를 만들지만, 이 페이지를 만듭니다. URL http://sites.google.com/site/siteName/files 아래 (http://sites.google.com/site/siteName/file-storage 대신) 이를 위해 <sites:pageName> 요소를 지정합니다.

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는 자료실 페이지 또는 상위 페이지에 첨부파일을 업로드할 수 있도록 지원합니다.

상위 항목에 첨부파일을 업로드하려면 콘텐츠 피드 URL에 HTTP POST 요청을 보냅니다.

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"));

웹 첨부파일

웹 첨부파일은 특별한 종류의 첨부파일입니다. 웹상의 다른 파일에 대한 링크이기 때문에 파일 캐비닛 목록에 추가할 수 있습니다. 이 기능은 'URL로 파일 추가' 업로드 방법을 사용할 수 있습니다.

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

이 예에서는 사용자의 콘텐츠 피드에 있는 첫 번째 FileCabinetPageEntry 아래에 WebAttachmentEntry를 만듭니다. 제목과 (선택사항) 설명이 'GoogleLogo'로 설정되어 있습니다. 각각 '좋은 색상'과 '좋은 색상'의 두 가지 조합을 제공합니다.

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() 메서드 사용 항목의 edit에 HTTP PUT 요청이 전송됩니다. 링크를 클릭합니다.

다음은 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 Sites에서 페이지나 항목을 삭제하려면 먼저 콘텐츠 항목을 가져온 다음 항목의 delete()를 호출합니다.

entry.delete();

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

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

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

맨 위로



첨부파일 다운로드

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

이 예에서는 사용자의 콘텐츠 피드에서 발견된 첫 번째 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 항목은 특정 항목(사용자, 사용자 그룹, 도메인)의 액세스 역할을 나타냅니다. 기본 액세스 (공개 사이트)를 지정할 수 있습니다. 명시적인 액세스 권한이 있는 법인의 항목만 표시됩니다. 항목 1개가 표시됩니다. '액세스 권한이 있는 사용자' 목록에서 Google Sites UI의 공유 화면에 있는 패널 따라서 도메인 관리자는 표시되지 않으며 사용자가 사이트에 액세스할 수 있습니다.

역할

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

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

범위

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

  • user — 이메일 주소 값(예: 'user@gmail.com')입니다.
  • group: Google 그룹 이메일 주소(예: 'group@domain.com')입니다.
  • domain — G Suite 도메인 이름(예: 'domain.com')입니다.
  • 기본값 — 값이 없는 '기본값' 유형의 가능한 범위는 하나만 있습니다. (예: <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);
}

가능한 AclScope를 보려면 ACL 피드 개요 섹션을 참고하세요. 및 AclRoles 값.

그룹 및 도메인 수준 공유

한 명의 사용자와 사이트를 공유하는 것과 마찬가지로 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을 수정합니다.

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

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 헤더에 대한 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\"");

서버는 이 요청을 수신할 때 요청한 항목에 대해 지정된 eType이 표시됩니다. 이 값이 일치하는 경우 항목은 변경되지 않았으며 서버는 HTTP 304 NotModifiedException 예외가 발생합니다.

infoType이 일치하지 않으면 마지막으로 요청한 이후 항목이 수정되고 서버가 항목을 반환합니다.

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

맨 위로