HTTP作為一個基礎功能,有必要介紹下在UWP下的使用方法。 一、Get請求: 一般我們用到的是GetAsync方法 上面方法中的前四行和後三行是等價的。 如果要讀取更多的信息,則用GetAsync讀取返回值的response。 二、Post請求: 一般來說,我們最常用的是發送一個json串返回也是 ...
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的介紹就到這裡了,如果還有其他的問題,歡迎留言或者聯繫我