windows C++-UWP 应用中使用 HttpRequest 类

在 UWP 应用中使用 HttpRequest 类

本节演示在 UWP 应用中如何使用 HttpRequest 类。 应用程序会提供一个输入框,该输入框定义了一个 URL 资源、用于执行 GET 和 POST 操作的按钮命令和用于取消当前操作的按钮命令。

使用 HttpRequest 类

1. 在 MainPage.xaml 中,如下所示定义 StackPanel 元素。

<StackPanel HorizontalAlignment="Left" Width="440"
            Background="{StaticResource ApplicationPageBackgroundThemeBrush}">
    <TextBox x:Name="InputTextBox" TextWrapping="Wrap" 
             Text="http://www.fourthcoffee.com/"/>
    <StackPanel Orientation="Horizontal">
        <Button x:Name="GetButton" Content="Get" Background="Green" 
            Click="GetButton_Click"/>
        <Button x:Name="PostButton" Content="Post" Background="Blue" 
            Click="PostButton_Click"/>
        <Button x:Name="CancelButton" Content="Cancel" Background="Red"
            IsEnabled="False" Click="CancelButton_Click"/>
        <ProgressRing x:Name="ResponseProgressRing" />
    </StackPanel>
    <TextBlock x:Name="ResponseTextBlock" TextWrapping="Wrap"/>
</StackPanel>

2. 在 MainPage.xaml.h 中,添加此 #include 指令:

#include "HttpRequest.h"

3. 在 MainPage.xaml.h 中,将这些 private 成员变量添加到 MainPage 类中:

// Produces HTTP requets.
Web::HttpRequest m_httpRequest;
// Enables us to cancel the active HTTP request.
concurrency::cancellation_token_source m_cancelHttpRequestSource;

4. 在 MainPage.xaml.h 中,声明 private 方法 ProcessHttpRequest:

// Displays the result of the provided HTTP request on the UI.
void ProcessHttpRequest(concurrency::task<std::wstring> httpRequest);

5. 在 MainPage.xaml.cpp 中,添加这些 using 语句:

using namespace concurrency;
using namespace std;
using namespace Web;

6. 在 MainPage.xaml.cpp 中,实现 GetButton_Click 类的 PostButton_Click、CancelButton_Click 和 MainPage 方法。

void MainPage::GetButton_Click(Object^ sender, RoutedEventArgs^ e)
{
    // Create a new cancellation token source for the web request.
    m_cancelHttpRequestSource = cancellation_token_source();

    // Set up the GET request parameters.
    auto uri = ref new Uri(InputTextBox->Text);
    auto token = m_cancelHttpRequestSource.get_token();

    // Send the request and then update the UI.
    ProcessHttpRequest(m_httpRequest.GetAsync(uri, token));
}

void MainPage::PostButton_Click(Object^ sender, RoutedEventArgs^ e)
{
    // Create a new cancellation token source for the web request.
    m_cancelHttpRequestSource = cancellation_token_source();

    // Set up the POST request parameters.
    auto uri = ref new Uri(InputTextBox->Text);
    wstring postData(L"This is sample POST data.");
    auto token = m_cancelHttpRequestSource.get_token();

    // Send the request and then update the UI.
    ProcessHttpRequest(m_httpRequest.PostAsync(uri, postData, token));
}

void MainPage::CancelButton_Click(Object^ sender, RoutedEventArgs^ e)
{
    // Disable the Cancel button.
    // It will be re-enabled during the next web request.
    CancelButton->IsEnabled = false;

    // Initiate cancellation.
    m_cancelHttpRequestSource.cancel();
}

如果你的应用程序不需要取消支持,请将 concurrency::cancellation_token::none 传递给 HttpRequest::GetAsync 和 HttpRequest::PostAsync 方法。

7. 在 MainPage.xaml.cpp 中,实现 MainPage::ProcessHttpRequest 方法。

// Displays the result of the provided HTTP request on the UI.
void MainPage::ProcessHttpRequest(task<wstring> httpRequest)
{
    // Enable only the Cancel button.
    GetButton->IsEnabled = false;
    PostButton->IsEnabled = false;
    CancelButton->IsEnabled = true;

    // Clear the previous response and start the progress ring.
    ResponseTextBlock->Text = "";
    ResponseProgressRing->IsActive = true;

    // Create a continuation that shows the results on the UI.
    // The UI must be updated on the ASTA thread. 
    // Therefore, schedule the continuation to run on the current context.
    httpRequest.then([this](task<wstring> previousTask)
    {
        try
        {
            //
            // Show the result on the UI.

            wstring response = previousTask.get();
            if (m_httpRequest.GetStatusCode() == 200)
            {
                // The request succeeded. Show the response.
                ResponseTextBlock->Text = ref new String(response.c_str());
            }
            else
            {
                // The request failed. Show the status code and reason.
                wstringstream ss;
                ss << L"The server returned "
                   << m_httpRequest.GetStatusCode()
                   << L" ("
                   << m_httpRequest.GetReasonPhrase()
                   << L')';
                ResponseTextBlock->Text = ref new String(ss.str().c_str());
            }
        }
        catch (const task_canceled&)
        {
            // Indicate that the operation was canceled.
            ResponseTextBlock->Text = "The operation was canceled";
        }
        catch (Exception^ e)
        {
            // Indicate that the operation failed.
            ResponseTextBlock->Text = "The operation failed";

            // TODO: Handle the error further.
            (void)e;
        }

        // Enable the Get and Post buttons.
        GetButton->IsEnabled = true;
        PostButton->IsEnabled = true;
        CancelButton->IsEnabled = false;

        // Stop the progress ring.
        ResponseProgressRing->IsActive = false;

    }, task_continuation_context::use_current());
}

8. 在项目属性中,在“链接器”的“输入”下,指定 shcore.lib 和 msxml6.lib。

这是正在运行的应用程序:

全文完。 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值