码迷,mamicode.com
首页 > Web开发 > 详细

UWP开发-HTTP详解

时间:2016-11-16 15:02:24      阅读:224      评论:0      收藏:0      [点我收藏+]

标签:foreach   uri   .post   get请求   .com   das   str   array   ref   

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详解

标签:foreach   uri   .post   get请求   .com   das   str   array   ref   

原文地址:http://www.cnblogs.com/Yixin-ran/p/6069029.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!