设为首页 加入收藏

TOP

UWP 使用Windows.Web.Http命名空间下的HttpClient使用post方法,上传图片服务器(二)
2017-10-11 14:34:31 】 浏览:2894
Tags:UWP 使用 Windows.Web.Http 命名 空间 HttpClient post 方法 上传 图片 服务器
ibility = Visibility.Collapsed; 37 } 38 catch (Exception ex) 39 { 40 System.Diagnostics.Debug.WriteLine(ex.Message + ex.StackTrace); 41 } 42 } 43 #endregion 44 }

 4.使用Windows.Web.Http命名空间下的HttpClient使用post方法,上传图片服务器

参考:https://social.msdn.microsoft.com/Forums/zh-CN/ec0ffd44-f7a6-4a53-8f8e-d15e13cfa5fb/windowswebhttphttpclientpost?forum=winstoreappzhcn

我的做法是将需要上传的参数放在HttpMultipartFormDataContent中,然后再使用HttpClient的PostAsync进行提交

请求参数:

 1       
 2        /// <summary>
 3         /// 向服务器发送post请求(修改头像)
 4         /// </summary>
 5         /// <param name="url">路径</param>
 6         /// <returns></returns>
 7         public async static Task<string> SendPostRequest(string url)
 8         {
 9             try
10             {
11                 Dictionary<string, object> dic = new Dictionary<string, object>();
12                 dic.Add("GWnumber", setHeadPicture.GWnumber);
13                 dic.Add("token", setHeadPicture.Token);
14                 dic.Add("file", setHeadPicture.File);//file值是StorageFile类型
15                 dic.Add("systemType", setHeadPicture.SystemType);
16 
17                 HttpMultipartFormDataContent form = new HttpMultipartFormDataContent();
18                 foreach (KeyValuePair<string, object> item in dic)
19                 {
20                     if (item.Key == "file")
21                     {
22                         StorageFile file = item.Value as StorageFile;
23                         HttpStreamContent streamContent = new HttpStreamContent(await file.OpenReadAsync());
24                         form.Add(streamContent, item.Key, "file.jpg");//注意:这里的值是必须的,图片所以使用的是HttpStreamContent
25                     }
26                     else
27                     {
28                         form.Add(new HttpStringContent(item.Value + ""), item.Key);
29                     }
30                 }
31                 HttpClient httpClient = new HttpClient();
32                 HttpResponseMessage response = await httpClient.PostAsync(new Uri(url), form).AsTask();
33                 var contentType = response.Content.Headers.ContentType;
34                 if (string.IsNullOrEmpty(contentType.CharSet))
35                 {
36                     contentType.CharSet = "utf-8";
37                 }
38                 return await response.Content.ReadAsStringAsync();
39 
40             }
41             catch (Exception ex)
42             {
43                 throw ;
44             }
45         }

uwp小白,请多指教!!

 

首页 上一页 1 2 下一页 尾页 2/2/2
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇UWP ObservableCollection<eva.. 下一篇UWP ObservableCollection<eva..

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目