UWP开发-HTTP详解

Posted Yixin-Ran

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了UWP开发-HTTP详解相关的知识,希望对你有一定的参考价值。

HTTP作为一个基础功能,有必要介绍下在UWP下的使用方法。

一、Get请求:

 一般我们用到的是GetAsync方法

 public static async Task Gets(Uri uri)
        {
            var response = await httpClient.GetAsync(uri);
            var str = await response.Content.ReadAsStringAsync();
            var stream = await response.Content.ReadAsInputStreamAsync();
            var buff = await response.Content.ReadAsBufferAsync();

            str = await httpClient.GetStringAsync(uri);
            stream = await httpClient.GetInputStreamAsync(uri);
            buff = await httpClient.GetBufferAsync(uri);
        }

上面方法中的前四行和后三行是等价的。

如果要读取更多的信息,则用GetAsync读取返回值的response。

二、Post请求:

一般来说,我们最常用的是发送一个json串返回也是json串,也就是application/json类型

 async public static Task<string> PostStringAsync(string url, string data)
        {
            try
            {
                HttpClient hc = new HttpClient();
                using (var content = new HttpStringContent(data))
                {
                    var response = await hc.PostAsync(new Uri(url), content);
                    var resdata = await response.Content.ReadAsStringAsync();
                    return resdata;
                }
            }
            catch
            {
                return null;
            }
        }

如果服务器要求的类型是表单类型,也就是x-www-form-urlencoded类型

 public async static Task<string> PostFormDataAsync(string url, List<KeyValuePair<string, string>> data)
        {
            try
            {
                HttpClient hc = new HttpClient();
                var content = new HttpFormUrlEncodedContent(data);
                var response = await hc.PostAsync(new Uri(url), content);
                var resdata = await response.Content.ReadAsStringAsync();
                Debug.WriteLine(resdata);
                return resdata;
            }
            catch
            {
                return null;
            }
        }
KeyValuePair的构造(注意这里只有string类型和数值类型,不能包含文件类型):
 public List<KeyValuePair<string, string>> CreatFormData<T>(T data)
        {
            List<KeyValuePair<string, string>> array = new List<KeyValuePair<string, string>>();
            var type = data.GetType();
            var propertyInfos = type.GetRuntimeProperties();
            foreach (var p in propertyInfos)
            {
                if (p.GetValue(data) != null)
                {
                    array.Add(new KeyValuePair<string, string>(p.Name, p.GetValue(data).ToString()));
                }
            }
            return array;
        }

如果要传的数据包含文件肿么办? 

第一种情况:只有文件 ,application/octet-stream

这种情况比较简单,构造一个HttpStreamContent就可以了:

 async public static Task<string> PostSteamAsync(string url, StorageFile file)
        {
            try
            {
                HttpClient hc = new HttpClient();
                using (var content = new HttpStreamContent(await file.OpenAsync(FileAccessMode.Read)))
                {
                    var response = await hc.PostAsync(new Uri(url), content);
                    var resdata = await response.Content.ReadAsStringAsync();
                    return resdata;
                }
            }
            catch
            {
                return null;
            }

        }

第二种情况:既有文件也有数据和字符串。也就是multipart/form-data类型

 /// <summary>
        /// 构造表单数据
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        async private static Task<HttpMultipartFormDataContent> ConstructMuilFromDataAsync(List<FormData> data)
        {
            var resdata = new HttpMultipartFormDataContent(boundary);
            foreach (var item in data)
            {
                if (item.File == null && !string.IsNullOrEmpty(item.Value))
                {
                    var scontent = new HttpStringContent(item.Value);
                    scontent.Headers.ContentDisposition = new HttpContentDispositionHeaderValue("form-data");
                    resdata.Add(scontent, item.Name);
                }
                else if (item.File != null)
                {
                    var stream = await item.File.OpenAsync(FileAccessMode.Read);

                    var buffcontent = new HttpStreamContent(stream);
                    buffcontent.Headers.ContentDisposition = new HttpContentDispositionHeaderValue("form-data");
                    buffcontent.Headers.ContentType = HttpMediaTypeHeaderValue.Parse(item.ContentType);
                    resdata.Add(buffcontent, item.Name, item.FileName);
                }
            }
            return resdata;
        }

  /// <summary>
        /// 发送复杂表单类型
        /// </summary>
        /// <param name="url"></param>
        /// <param name="data"></param>
        /// <returns></returns>
        async public static Task<string> PostMuilFormDataAsync(string url, List<FormData> data)
        {
            try
            {
                HttpClient hc = new HttpClient();
                var content = await ConstructMuilFromDataAsync(data);
                var response = await hc.PostAsync(new Uri(url), content);
                var resdata = await response.Content.ReadAsStringAsync();
                Debug.WriteLine(resdata);
                return resdata;
            }
            catch
            {
                return null;
            }
        }
///自定义FormData类
public class FormData
    {
        private string _name;
        private string _value;
        private string _type;
        public string Name
        {
            get { return _name; }
            set { _name = value; }
        }
        public string Value
        {
            get { return _value; }
            set { _value = value; }
        }
        public string ContentType
        {
            get { return _type; }
            set { _type = value; }
        }
        public StorageFile File { get; set; }
        public string FileName { get; set; }
       
    }

关于这段的FormData是我自己构造的,如果你有更好的方法,请告诉我。其中ContenType:Image为”Image/jpeg“;MP3为”Audio/MP3“;MP4为”Video/MP4“关于其他的则可以自行在网络上查询。

  好了,关于Http的介绍就到这里了,如果还有其他的问题,欢迎留言或者联系我

以上是关于UWP开发-HTTP详解的主要内容,如果未能解决你的问题,请参考以下文章

UWP开发之Mvvmlight实践四:{x:bind}和{Binding}区别详解

韩剧TV UWP开发---抓包分析

高效Web开发的10个jQuery代码片段

Mvvmlight实践一:如果在项目中添加使用Mvvmlight(图文详解)

前端开发常用代码片段(中篇)

IOS开发-OC学习-常用功能代码片段整理