当前位置: 首页 > news >正文

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。

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

全文完。 

相关文章:

  • 微软开源项目 Detours 详细介绍与使用实例分享
  • JetLinks物联网平台微服务化系列文章介绍
  • linux 目录文件夹操作
  • 使用 Docker 制作 YashanDB 镜像:深度解析与实战指南
  • 番外篇 | 复现AC-YOLOv5,进行自动化织物缺陷检测
  • CSP-J 复赛算法 贪心策略应用
  • 棒材翘头翘尾影响大 在线直线度测量仪监测保品质!
  • index.html 调用 ajax
  • [spring]SpringBoot拦截器 统一数据返回格式 统一异常处理
  • QML使用Qt自带软键盘例子
  • Robot Operating System——带有协方差矩阵的三维空间中的位姿(位置和方向)
  • 成都睿明智科技有限公司赋能商家高效变现
  • OpenHarmony(鸿蒙南向)——平台驱动开发【PIN】
  • N诺计算机考研-错题(DS)
  • Qt C++设计模式->享元模式
  • JavaScript-如何实现克隆(clone)函数
  • 【vuex入门系列02】mutation接收单个参数和多个参数
  • 【面试系列】之二:关于js原型
  • ComponentOne 2017 V2版本正式发布
  • jdbc就是这么简单
  • Mithril.js 入门介绍
  • php ci框架整合银盛支付
  • SpiderData 2019年2月13日 DApp数据排行榜
  • Traffic-Sign Detection and Classification in the Wild 论文笔记
  • vue学习系列(二)vue-cli
  • Web设计流程优化:网页效果图设计新思路
  • 从地狱到天堂,Node 回调向 async/await 转变
  • 观察者模式实现非直接耦合
  • 开源中国专访:Chameleon原理首发,其它跨多端统一框架都是假的?
  • 聊聊sentinel的DegradeSlot
  • 使用 Docker 部署 Spring Boot项目
  • 使用前端开发工具包WijmoJS - 创建自定义DropDownTree控件(包含源代码)
  • 吴恩达Deep Learning课程练习题参考答案——R语言版
  • 原生js练习题---第五课
  • Oracle Portal 11g Diagnostics using Remote Diagnostic Agent (RDA) [ID 1059805.
  • 长三角G60科创走廊智能驾驶产业联盟揭牌成立,近80家企业助力智能驾驶行业发展 ...
  • ​【原创】基于SSM的酒店预约管理系统(酒店管理系统毕业设计)
  • ​香农与信息论三大定律
  • #### go map 底层结构 ####
  • #我与Java虚拟机的故事#连载10: 如何在阿里、腾讯、百度、及字节跳动等公司面试中脱颖而出...
  • (4) PIVOT 和 UPIVOT 的使用
  • (4)(4.6) Triducer
  • (6)设计一个TimeMap
  • (C语言版)链表(三)——实现双向链表创建、删除、插入、释放内存等简单操作...
  • (Java实习生)每日10道面试题打卡——JavaWeb篇
  • (Oracle)SQL优化技巧(一):分页查询
  • (PySpark)RDD实验实战——取一个数组的中间值
  • (附源码)计算机毕业设计SSM疫情下的学生出入管理系统
  • (强烈推荐)移动端音视频从零到上手(上)
  • (求助)用傲游上csdn博客时标签栏和网址栏一直显示袁萌 的头像
  • (一) storm的集群安装与配置
  • (转)Sql Server 保留几位小数的两种做法
  • (转)负载均衡,回话保持,cookie
  • (转)关于多人操作数据的处理策略
  • (转)视频码率,帧率和分辨率的联系与区别