웹 피드에 액세스하는 방법(HTML)

[ 이 문서는 Windows 런타임 앱을 작성하는 Windows에서 8.x 및 Windows Phone 8.x 개발자를 대상으로 합니다. Windows 10용으로 개발하는 경우에는 최신 설명서를 참조하세요.]

이 항목에서는 Windows 런타임 앱에서 Windows.Web.Syndication 네임스페이스의 클래스를 사용하여 웹 피드를 검색하고 표시하는 방법을 보여 줍니다.

사전 요구 사항

다음 예는 JavaScript를 사용하며 신디케이션 샘플을 기반으로 합니다. JavaScript를 사용하여 Windows 런타임 앱을 만드는 방법에 대한 일반적인 내용은 JavaScript를 사용하여 첫 번째 Windows 런타임 앱 만들기를 참조하세요. 또한 JavaScript Promise는 이 항목에서 비동기 작업을 완료하는 데 사용됩니다. 이 프로그래밍 패턴에 대한 자세한 내용은 Promises를 사용하는 JavaScript의 비동기 프로그래밍을 참조하세요.

Windows 런타임 앱에서 네트워크에 대비하려면 프로젝트 Package.appxmanifest 파일에 필요한 네트워크 접근 권한 값을 설정해야 합니다. 앱이 인터넷의 원격 서비스에 클라이언트로 연결해야 하는 경우 인터넷(클라이언트) 접근 권한 값이 필요합니다. 앱이 홈 네트워크 또는 회사 네트워크의 원격 서비스에 클라이언트로 연결해야 하는 경우 홈/회사 네트워킹 접근 권한 값이 필요합니다. 자세한 내용은 네트워크 접근 권한 값을 설정하는 방법을 참조하세요.

지침

웹 피드에서 신디케이티드 콘텐츠 검색

이제 피드를 검색한 다음 피드에 포함된 개별 항목을 표시하는 방법을 보여 주는 일부 코드를 검토합니다. 요청을 구성하여 보내려면 먼저 작업 중 사용할 몇 가지 변수를 정의하고 피드를 검색 및 표시할 때 사용할 메서드와 속성을 정의하는 SyndicationClient의 인스턴스를 초기화합니다.

생성자에 전달된 uriString이 유효한 URI가 아니면 Uri 생성자에서 예외가 발생합니다. 따라서 try/catch 블록을 사용하여 uriString의 유효성을 검사합니다.

var currentFeed = null;
var currentItemIndex = 0;
        
var client = new Windows.Web.Syndication.SyndicationClient();

// The URI is validated by catching exceptions thrown by the Uri constructor.
var uri = null;
try {
    uri = new Windows.Foundation.Uri(uriString);
} catch (error) {
    WinJS.log && WinJS.log("Error: Invalid URI");
    return;
}

다음에는 필요한 서버 자격 증명(serverCredential 속성), 프록시 자격 증명(proxyCredential 속성) 및 HTTP 헤더(setRequestHeader 메서드)를 설정하여 요청을 구성합니다. 기본 요청 매개 변수를 구성하면 앱에서 제공한 피드 URI 문자열을 사용하여 유효한 Uri 개체가 만들어집니다. 그런 다음 피드를 요청하기 위해 Uri 개체가 retrieveFeedAsync 함수에 전달됩니다.

필요한 피드 콘텐츠가 반환된 경우 코드는 다음에 정의하는 displayCurrentItem을 호출하여 각 피드 항목을 반복하여 UI를 통해 항목과 해당 콘텐츠를 목록으로 표시합니다.

따라서 대부분의 비동기 네트워크 메서드를 호출할 때 예외를 처리하는 코드를 작성해야 합니다. 예외 처리기는 예외의 원인에 대해 보다 자세한 정보를 검색하므로 오류를 더 잘 이해하고 적절한 의사 결정을 내릴 수 있습니다. 자세한 내용은 네트워크 앱에서 예외를 처리하는 방법을 참조하세요.

HTTP 서버에 연결할 수 없거나 Uri 개체가 유효한 AtomPub 또는 RSS 피드를 가리키지 않는 경우 retrieveFeedAsync 메서드에서 예외가 발생합니다. 샘플 코드는 onError 함수를 사용하여 예외를 catch하고, 오류가 발생할 경우 예외에 대한 자세한 정보를 출력합니다.

function onError(err) {
    WinJS.log && WinJS.log(err, "sample", "error");

    // Match error number with a ErrorStatus value.
    // Use Windows.Web.WebErrorStatus.getStatus() to retrieve HTTP error status codes.
    var errorStatus = Windows.Web.Syndication.SyndicationError.getStatus(err.number);
    if (errorStatus === Windows.Web.Syndication.SyndicationErrorStatus.invalidXml) {
        displayLog("An invalid XML exception was thrown. Please make sure to use a URI that points to a RSS or Atom feed.");
    }
}

// Retrieve and display feed at given feed address.
function retreiveFeed(uri) {

    // Although most HTTP servers do not require User-Agent header, 
    // others will reject the request or return a different response if this header is missing.
    // Use the setRequestHeader() method to add custom headers.
    client.setRequestHeader("User-Agent", "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; WOW64; Trident/6.0)");

    client.retrieveFeedAsync(uri).done(function (feed) {
        currentFeed = feed;

        WinJS.log && WinJS.log("Feed download complete.", "sample", "status");

        var title = "(no title)";
        if (currentFeed.title) {
            title = currentFeed.title.text;
        }
        document.getElementById("CurrentFeedTitle").innerText = title;

        currentItemIndex = 0;
        if (currentFeed.items.size > 0) {
            displayCurrentItem();
        }

        // List the items.
        displayLog("Items: " + currentFeed.items.size);
     }, onError);
}

이전 단계에서 retrieveFeedAsync는 요청된 피드 콘텐츠를 반환했고 예제 코드에서는 사용 가능한 피드 항목을 반복했습니다. 이러한 각 항목은 관련 신디케이션 표준(RSS 또는 Atom)에서 제공하는 모든 항목 속성과 콘텐츠를 포함하는 SyndicationItem 개체를 사용하여 나타냅니다. 다음 예제에서는 각 항목을 처리하고 다양한 이름의 UI 요소를 통해 항목의 콘텐츠를 표시하는 displayCurrentItem 함수를 관찰합니다.

function displayCurrentItem() {
    var item = currentFeed.items[currentItemIndex];

    // Display item number.
    document.getElementById("Index").innerText = (currentItemIndex + 1) + " of " + currentFeed.items.size;

    // Display title.
    var title = "(no title)";
    if (item.title) {
        title = item.title.text;
    }
    document.getElementById("ItemTitle").innerText = title;

    // Display the main link.
    var link = "";
    if (item.links.size > 0) {
        link = item.links[0].uri.absoluteUri;
    }

    var link = document.getElementById("Link");
    link.innerText = link;
    link.href = link;

    // Display the body as HTML.
    var content = "(no content)";
    if (item.content) {
        content = item.content.text;
    }
    else if (item.summary) {
        content = item.summary.text;
    }
    document.getElementById("WebView").innerHTML = window.toStaticHTML(content);

앞에서 설명한 대로 SyndicationItem 개체로 표시되는 콘텐츠 유형은 피드를 게시하는 데 사용된 피드 표준(RSS 또는 Atom)에 따라 달라집니다. 예를 들어 Atom 피드는 contributors 목록을 제공할 수 있지만 RSS 피드는 제공할 수 없습니다. 그러나 한쪽 표준에서 지원되지 않는 피드 항목에 포함된 확장 요소(예: 더블린 코어 확장 요소)는 다음 예제 코드에 나온 대로 SyndicationItem.elementExtensions 속성을 사용하여 액세스한 다음 표시할 수 있습니다.


    // displayCurrentItem function continued
    var bindableNodes = [];
    for (var i = 0; i < item.elementExtensions.size; i++) {
        var bindableNode = {
            nodeName: item.elementExtensions[i].nodeName,
             nodeNamespace: item.elementExtensions[i].nodeNamespace,
             nodeValue: item.elementExtensions[i].nodeValue,
        };
        bindableNodes.push(bindableNode);
    }

    var dataList = new WinJS.Binding.List(bindableNodes);
    var listView = document.getElementById("extensionsListView").winControl;
    WinJS.UI.setOptions(listView, {
        itemDataSource: dataList.dataSource

    });
}

요약 및 다음 단계

이 항목에서는 제공된 URI와 연결된 피드를 검색하고 피드 콘텐츠 항목을 항목별로 표시했습니다.

웹 피드 내 항목을 추가, 편집 및 삭제할 수 있는 등의 고급 기능을 보려면 웹 피드 항목을 관리하는 방법을 참조하세요.

관련 항목

기타

promises를 사용한 JavaScript의 비동기 프로그래밍

네트워크 접근 권한 값을 설정하는 방법

네트워크 앱에서 예외를 처리하는 방법

웹 피드 항목을 관리하는 방법

JavaScript로 작성한 Windows 런타임 앱용 로드맵

참조

SyndicationClient

SyndicationItem

Windows.Web.AtomPub

Windows.Web.Syndication

샘플

AtomPub 샘플

신디케이션 샘플