Share via


Web フィード エントリを管理する方法 (HTML)

[ この記事は、Windows ランタイム アプリを作成する Windows 8.x および Windows Phone 8.x 開発者を対象としています。Windows 10 向けの開発を行っている場合は、「最新のドキュメント」をご覧ください]

このトピックでは、Windows ランタイムにおける Atom Publication プロトコルの実装である Windows.Web.AtomPub 名前空間を使って、サービス ドキュメントにアクセスし、そこに含まれているフィード リソースに変更を加える方法について説明します。

必要条件

次の例は、JavaScript で記述されており、AtomPub のサンプルに基づいています。 JavaScript を使った Windows ランタイム アプリの作成についての一般的なヘルプは、「JavaScript を使った初めての Windows ランタイム アプリの作成」をご覧ください。このトピックでは、JavaScript の promise を使って非同期操作も実行します。このプログラミング パターンについて詳しくは、promise を使った JavaScript での非同期プログラミングに関するページをご覧ください。

Windows ランタイム アプリをネットワークに対応させるには、プロジェクトの Package.appxmanifest ファイルで必要なネットワーク機能を設定する必要があります。 アプリがクライアントとしてインターネット上のリモート サービスに接続する必要がある場合は、インターネット (クライアント) 機能が必要です。アプリがクライアントとしてホーム ネットワークまたは社内ネットワーク上のリモート サービスに接続する必要がある場合は、ホーム/社内ネットワーク機能が必要です。詳しくは、「ネットワーク機能を設定する方法」をご覧ください。

手順

1. サービス ドキュメント

コード例を見ていく前に、サービス ドキュメントを使って Web サービスのフィード コンテンツの構造を定義する方法について、基本を理解しておいてください。

サービス ドキュメントには、ワークスペース (workspace) 要素が少なくとも 1 つカプセル化されています。ワークスペースは、1 つ以上のコレクションを表します。つまり、個人ブログや Web ページなどの Web パブリケーションはワークスペースと考えられ、含まれているコレクションは個々のフィードを表します。個々のフィードにはさまざまなエントリが含まれます。

次の構文は、簡単なサービス ドキュメントの例です。

<?xml version="1.0" encoding='utf-8'?>
<service xmlns="http://www.w3.org/2007/app"
         xmlns:atom="http://www.w3.org/2005/Atom">
    <workspace>
        <atom:title>Main Site</atom:title>
        <collection
            href="http://example.org/blog/main" >
            <atom:title>My Blog Entries</atom:title>
            <categories
               href="http://example.com/cats/forMain.cats" />
        </collection>
        <collection
            href="http://example.org/blog/pic" >
            <atom:title>Pictures</atom:title>
            <accept>image/png</accept>
            <accept>image/jpeg</accept>
            <accept>image/gif</accept>
        </collection>
    </workspace>
</service>

サービス ドキュメントを取得するには、関連付けられている UriretrieveServiceDocumentAsync に渡します。特定のフィード エントリをアプリで取得、編集、削除するには、個々のエントリに関連付けられている絶対 URI ごとに、取得した ServiceDocument を解析する必要があります。

2. 認証資格情報を使ったクライアントの初期化

以下の例では、フィード管理操作に Windows.Web.AtomPub 名前空間のクラスを使い、個々のフィード要素を表すために Windows.Web.Syndication 名前空間のクラスを使います。また、ほとんどの Web 発行サービスには、特定の形式の認証が必要となります。この機能は、Windows.Security 名前空間に用意されています。

次の例では、AtomPubClient インスタンスの初期化処理で、資格情報を設定して取り込んでいます。


//define some variables

// The default values for the site.
var baseUri = "http://<Your Wordpress Site>.wordpress.com/";
var user = "";
var password = "";

// The default Service Document and Edit 'URIs'
var editUri = "./wp-app.php/posts";
var serviceDocUri = "./wp-app.php/service";
var feedUri = "./?feed=atom";
var currentFeed = null;
var currentItemIndex = 0;
        
var client;

var item;

// Get current credentialS and create the AtomPub client
function createClient() {
    client = new Windows.Web.AtomPub.AtomPubClient();
    // Don't save the results to the client's cache
    client.bypassCacheOnRetrieve = true;

    if ((user !== "") && (password !== "")) {
        var credential = new Windows.Security.Credentials.PasswordCredential();
        credential.userName = user;
        credential.password = password;
        client.serverCredential = credential;
    }
    else {
        client.serverCredential = null;
    }
}

3. コレクション内への新しい投稿の作成

既にあるコレクションに新しい投稿を追加するには、新しい SyndicationItem オブジェクトを作り、そこに必要なコンテンツを設定します。SyndicationItem が完成したら、そのオブジェクトと、エントリについて簡潔に説明する文字列、さらにフィードの Uri を、AtomPubClientcreateResourceAsync メソッドに渡します。

Uri コンストラクターは、渡された uriString が有効な URI ではない場合、例外をスローします。そのため、try/catch ブロックを使用して uriString を検証します。

非同期ネットワーク メソッドの多くは、呼び出す場合、例外を処理するようにコードを記述する必要があります。エラーについてよく理解し、適切な判断ができるように、例外ハンドラーは例外の原因についての詳しい情報を取得できます。詳しくは、「ネットワーク アプリで例外を処理する方法」をご覧ください。

createResourceAsync メソッドは、ネットワーク サーバーとの TCP 接続が確立できなかった場合や、Uri オブジェクトが有効な AtomPub や RSS フィードを指していない場合、例外をスローします。サンプル コードでは、onError 関数を使って、エラーが発生した場合に例外をキャッチし、例外に関する詳細な情報を出力します。

// Called when an async function generates an error.
function onError(err) {
    displayError(err);

    // Match error number with a WebErrorStatus value, in order to deal
    // with a specific error.
    var errorStatus = Windows.Web.WebError.getStatus(err.number);
    if (errorStatus === Windows.Web.WebErrorStatus.unauthorized) {
        displayLog("Wrong username or password!");
    }
}

function createPost (uriString, postTitle, postContent, postSummary, postAuthor) {

    var resourceUri;
    try {
        resourceUri = new Windows.Foundation.Uri(uriString);
    } catch (error) {
        displayLog("Error: Invalid URI");
    return;

    var syndicationItem;

    item = new Windows.Web.Syndication.SyndicationItem();
    item.title = new Windows.Web.Syndication.SyndicationText(postTitle);
    item.summary = new Windows.Web.Syndication.SyndicationText(postSummary);
    item.content = new Windows.Web.Syndication.SyndicationContent(postContent, Windows.Web.Syndication.SyndicationTextType.Text);
    item.authors[0] = new Windows.Web.Syndication.SyndicationPerson(postAuthor);
    // Note: Also other item fields can be set such as 'syndicationItem.Categories[0]'

    return client.createResourceAsync(resourceUri, item.title.text, item);
}).done(function (result) {
    if (result) {
        displayLog("Posted at " + result.editUri.displayUri);
        displayLog("New post created.");
    }
 }, onError);

4. コレクション内の投稿の編集

コレクション内に既にあるエントリを編集するには、関連付けられている UriSyndicationClientretrieveFeedAsync メソッドに渡します。新しい値の SyndicationItem を準備し、そのオブジェクトを、エントリを取得するときに使った Uri と一緒に AtomPubClientupdateResourceAsync に渡します。

function editPost (uriString, postTitle, postContent, postSummary, postAuthor) {

    var resourceUri;
    try {
        resourceUri = new Windows.Foundation.Uri(uriString);
    } catch (error) {
        displayLog("Error: Invalid URI");
    return;

    var updatedItem = new Windows.Web.Syndication.SyndicationItem();
    updatedItem.title = new Windows.Web.Syndication.SyndicationText(postTitle);
    updatedItem.summary = new Windows.Web.Syndication.SyndicationText(postSummary);
    updatedItem.content = new Windows.Web.Syndication.SyndicationContent(postContent, Windows.Web.Syndication.SyndicationTextType.Text);
    updatedItem.authors[0] = new Windows.Web.Syndication.SyndicationPerson(postAuthor);
    // Note: Also other item fields can be set such as 'syndicationItem.Categories[0]'

    client.updateResourceAsync(resourceUri, updatedItem).done(function () {
        displayLog("Updating item completed.");
    }
 }, onError);
}

5. コレクションからの投稿の削除

コレクションからのエントリを削除するには、SyndicationItem インスタンスの editUri プロパティを AtomPubClient インスタンスの deleteResourceItemAsync メソッドに渡します。

function deletePost(uriString, currentFeed) {

    var resourceUri;
    try {
        resourceUri = new Windows.Foundation.Uri(uriString);
    } catch (error) {
        displayLog("Error: Invalid URI");
    return;

   // If we retrieve the feed via the resourceUri then we will be logged in and will be
   // able to modify/delete the resource.

   client.retrieveFeedAsync(resourceUri).done(function (feed) {
       currentFeed = feed;
       currentItemIndex = 0;

       displayLog("Got feed");
       var title = "(no title)";
       if (currentFeed.title) {
           title = currentFeed.title.text;
       }
       displayLog("Title: " + title);

       var currentItem = getCurrentItem();
       if (currentItem) {
           displayLog("EditUri: " + currentItem.editUri);
       }

       displayStatus("Fetching feed completed.");
   }, onError);
    
   client.deleteResourceItemAsync(currentItem).done(function() {
       displayLog("Deleting item completed.");
    
       // Our feed is now out of date.  Re-fetch the feed before deleting something else.
       currentFeed = null;
    }, onError);
    }

要約と次のステップ

このトピックでは、サービス ドキュメントを取得し、ドキュメント内で新しいコレクション エントリを追加したり、既にあるコレクション エントリに変更を加えたり、コレクション エントリを削除したりする方法を紹介しました。基本的なフィード取得の簡単なデモについては、「Web フィードにアクセスする方法」をご覧ください。

関連トピック

その他

promise を使った JavaScript での非同期プログラミングに関する記事

ネットワーク機能を設定する方法

ネットワーク アプリで例外を処理する方法

Web フィードにアクセスする方法

JavaScript を使った Windows ランタイム アプリのためのロードマップ

リファレンス

AtomPubClient

SyndicationItem

Windows.Web.AtomPub

Windows.Web.Syndication

サンプル

AtomPub のサンプル

Syndication のサンプルに関するページ