如何:連接至 HTTP 伺服器 (C++ REST SDK)

利用 C++ REST SDK (代號名稱 "Casablanca"),您可以更容易從 C++ 應用程式連接至 HTTP 伺服器。 這個頁面顯示三個範例。 第一個範例示範建立 HTTP GET 要求及接收回應的基本方式。 第二個範例與第一個範例相似,但會建置使用自訂標頭值的 HTTP 要求。 第三個範例示範如何使用 HTTP PUT 將檔案上傳至伺服器。

這些範例後面還有顯示 #include 和 using 陳述式的較完整範例。

警告

此主題包含 C++ REST SDK 1.0 (代號名稱 "Casablanca") 的相關資訊。如果您是使用 Codeplex Casablanca 網頁 提供的較新版本,則請使用位於 http://casablanca.codeplex.com/documentation 的本機說明文件。

建立 HTTP GET 要求及接收回應

以下是使用 web::http::client::http_client 類別來建立 HTTP GET 要求的方法。 web::http::client::http_response 類別代表伺服器的回應。 如需將 HTTP 回應處理成 JSON 資料的類似範例,請參閱<如何:使用 JSON 資料>。

// Creates an HTTP request and prints the length of the response stream.
pplx::task<void> HTTPStreamingAsync()
{
    http_client client(L"https://www.fourthcoffee.com");

    // Make the request and asynchronously process the response.
    return client.request(methods::GET).then([](http_response response)
    {
        // Print the status code.
        std::wostringstream ss;
        ss << L"Server returned returned status code " << response.status_code() << L'.' << std::endl;
        std::wcout << ss.str();

        // TODO: Perform actions here reading from the response stream.
        auto bodyStream = response.body();

        // In this example, we print the length of the response to the console.
        ss.str(std::wstring());
        ss << L"Content length is " << response.headers().content_length() << L" bytes." << std::endl;
        std::wcout << ss.str();
    });

    /* Sample output:
    Server returned returned status code 200.
    Content length is 63803 bytes.
    */
}

建立使用自訂標頭值的 HTTP GET 要求

此範例類似上一個範例,但其使用 web::http::client::http_request 類別,以手動建立要求標頭。

// Builds an HTTP request that uses custom header values.
pplx::task<void> HTTPRequestCustomHeadersAsync()
{
    http_client client(L"https://www.fourthcoffee.com");

    // Manually build up an HTTP request with header and request URI.
    http_request request(methods::GET);
    request.headers().add(L"MyHeaderField", L"MyHeaderValue");
    request.set_request_uri(L"requestpath");
    return client.request(request).then([](http_response response)
    {
        // Print the status code.
        std::wostringstream ss;
        ss << L"Server returned returned status code " << response.status_code() << L"." << std::endl;
        std::wcout << ss.str();
    });

    /* Sample output:
    Server returned returned status code 200.
    */
}

使用 HTTP PUT 將檔案上傳至伺服器

此範例類似第一個範例,但其使用 concurrency::streams::file_stream 類別,以非同步方式從磁碟讀取檔案。 Concurrency::streams::basic_istream 物件會保存檔案內容。 此範例使用 web::http::methods::PUT,將作業指定為 HTTP PUT 作業。 如需使用資料流的更多範例,請參閱<如何:使用非同步資料流>。

// Upload a file to an HTTP server.
pplx::task<void> UploadFileToHttpServerAsync()
{
    using concurrency::streams::file_stream;
    using concurrency::streams::basic_istream;

    // To run this example, you must have a file named myfile.txt in the current folder.
    // Alternatively, you can use the following code to create a stream from a text string.
    // std::string s("abcdefg");
    // auto ss = concurrency::streams::stringstream::open_istream(s);

    // Open stream to file.
    return file_stream<unsigned char>::open_istream(L"myfile.txt").then([](pplx::task<basic_istream<unsigned char>> previousTask)
    {
        try
        {
            auto fileStream = previousTask.get();

            // Make HTTP request with the file stream as the body.
            http_client client(L"https://www.fourthcoffee.com");
            return client.request(methods::PUT, L"myfile", fileStream).then([fileStream](pplx::task<http_response> previousTask)
            {
                fileStream.close();

                std::wostringstream ss;
                try
                {
                    auto response = previousTask.get();
                    ss << L"Server returned returned status code " << response.status_code() << L"." << std::endl;
                }
                catch (const http_exception& e)
                {
                    ss << e.what() << std::endl;
                }
                std::wcout << ss.str();
            });
        }
        catch (const std::system_error& e)
        {
            std::wostringstream ss;
            ss << e.what() << std::endl;
            std::wcout << ss.str();

            // Return an empty task.
            return pplx::task_from_result();
        }
    });

    /* Sample output:
    The request must be resent
    */
}

完整範例

以下是完整的範例。

// basic-http-client.cpp
#include <http_client.h>
#include <filestream.h>
#include <iostream>
#include <sstream>

using namespace web::http;
using namespace web::http::client;

// Creates an HTTP request and prints the length of the response stream.
pplx::task<void> HTTPStreamingAsync()
{
    http_client client(L"https://www.fourthcoffee.com");

    // Make the request and asynchronously process the response.
    return client.request(methods::GET).then([](http_response response)
    {
        // Print the status code.
        std::wostringstream ss;
        ss << L"Server returned returned status code " << response.status_code() << L'.' << std::endl;
        std::wcout << ss.str();

        // TODO: Perform actions here reading from the response stream.
        auto bodyStream = response.body();

        // In this example, we print the length of the response to the console.
        ss.str(std::wstring());
        ss << L"Content length is " << response.headers().content_length() << L" bytes." << std::endl;
        std::wcout << ss.str();
    });

    /* Sample output:
    Server returned returned status code 200.
    Content length is 63803 bytes.
    */
}

// Builds an HTTP request that uses custom header values.
pplx::task<void> HTTPRequestCustomHeadersAsync()
{
    http_client client(L"https://www.fourthcoffee.com");

    // Manually build up an HTTP request with header and request URI.
    http_request request(methods::GET);
    request.headers().add(L"MyHeaderField", L"MyHeaderValue");
    request.set_request_uri(L"requestpath");
    return client.request(request).then([](http_response response)
    {
        // Print the status code.
        std::wostringstream ss;
        ss << L"Server returned returned status code " << response.status_code() << L"." << std::endl;
        std::wcout << ss.str();
    });

    /* Sample output:
    Server returned returned status code 200.
    */
}

// Upload a file to an HTTP server.
pplx::task<void> UploadFileToHttpServerAsync()
{
    using concurrency::streams::file_stream;
    using concurrency::streams::basic_istream;

    // To run this example, you must have a file named myfile.txt in the current folder.
    // Alternatively, you can use the following code to create a stream from a text string.
    // std::string s("abcdefg");
    // auto ss = concurrency::streams::stringstream::open_istream(s);

    // Open stream to file.
    return file_stream<unsigned char>::open_istream(L"myfile.txt").then([](pplx::task<basic_istream<unsigned char>> previousTask)
    {
        try
        {
            auto fileStream = previousTask.get();

            // Make HTTP request with the file stream as the body.
            http_client client(L"https://www.fourthcoffee.com");
            return client.request(methods::PUT, L"myfile", fileStream).then([fileStream](pplx::task<http_response> previousTask)
            {
                fileStream.close();

                std::wostringstream ss;
                try
                {
                    auto response = previousTask.get();
                    ss << L"Server returned returned status code " << response.status_code() << L"." << std::endl;
                }
                catch (const http_exception& e)
                {
                    ss << e.what() << std::endl;
                }
                std::wcout << ss.str();
            });
        }
        catch (const std::system_error& e)
        {
            std::wostringstream ss;
            ss << e.what() << std::endl;
            std::wcout << ss.str();

            // Return an empty task.
            return pplx::task_from_result();
        }
    });

    /* Sample output:
    The request must be resent
    */
}

int wmain()
{
    // This example uses the task::wait method to ensure that async operations complete before the app exits. 
    // In most apps, you typically don�t wait for async operations to complete.

    std::wcout << L"Calling HTTPStreamingAsync..." << std::endl;
    HTTPStreamingAsync().wait();

    std::wcout << L"Calling HTTPRequestCustomHeadersAsync..." << std::endl;
    HTTPRequestCustomHeadersAsync().wait();

    std::wcout << L"Calling UploadFileToHttpServerAsync..." << std::endl;
    UploadFileToHttpServerAsync().wait();
}

請參閱

其他資源

C++ REST SDK (Codename "Casablanca")