• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
手写的从前
博客园    首页    新随笔    联系   管理    订阅  订阅

Windows Phone 十六、HttpClient

HttpClient 对象也可以实现网络请求

相对于 HttpWebRequest 对象来说,HttpClient 操作更简单,功能更强大

HttpClient 提供一系列比较简单的API来实现基本的请求

同时也支持身份验证和异步操作

注意 Windows Runtime 平台中有两个 HttpClient 类型,调用方式几乎相同,以下内容使用 Windows.Web.Http 中的 HttpClient

发送数据格式

HttpFormUrlEncodedContent

HttpMultipartContent

HttpMultipartFormDataContent

HttpBufferContent

HttpStreamContent

HttpStringContent

设置 Cookie:client.DefaultRequestHeaders.Add("Cookie", "cookie_key1=CookieValue1; cookie_key2=CookieValue2;");

1     <Grid>
2         <TextBox x:Name="txtUrl"/>
3         <Button Content="DOWN" Click="Button_Click"/>
4     </Grid>
 1         protected async override void OnNavigatedTo(NavigationEventArgs e)
 2         {
 3             HttpClient client = new HttpClient();
 4             client.DefaultRequestHeaders.Authorization = new Windows.Web.Http.Headers.HttpCredentialsHeaderValue("Basic", "111:222");
 5             //GET请求
 6             var result = await client.GetStringAsync(new Uri("http://localhost:7080/index.ashx"));
 7 
 8             var dict = new Dictionary<string, string>();
 9             dict.Add("ke1", "val1");
10             dict.Add("ke2", "val2");
11             //await client.PostAsync(new Uri("http://localhost:7080/index.ashx"), new HttpFormUrlEncodedContent(dict));
12             //await client.PostAsync(new Uri("http://localhost:7080/index.ashx"), new HttpStringContent("abc"));
13 
14             var file = await ApplicationData.Current.LocalCacheFolder.CreateFileAsync("1.txt", CreationCollisionOption.ReplaceExisting);
15             await FileIO.AppendTextAsync(file, "abcdefghijklmnopqrstuvwxyz");
16             var fileStream = await file.OpenAsync(FileAccessMode.Read);
17             await client.PostAsync(new Uri("http://localhost:7080/index.ashx"), new HttpStreamContent(fileStream));
18         }
19 
20         private async void Button_Click(object sender, RoutedEventArgs e)
21         {
22             //定义请求Uri
23             var requestUri = new Uri(txtUrl.Text);
24             //创建一个Http请求客户端HttpClient
25             var client = new HttpClient();
26             //创建定期监视对象
27             IProgress<HttpProgress> progress = new Progress<HttpProgress>((p) =>
28             {
29                 //此处参数P,可以获取到进度相关信息
30                 System.Diagnostics.Debug.WriteLine(p.BytesReceived + "/" + p.TotalBytesToReceive);
31             });
32             //在异步任务中加入进度监控
33             HttpResponseMessage response = await client.GetAsync(requestUri).AsTask(progress);
34         }

 

posted @ 2015-06-25 02:53  手写从前  阅读(473)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3