/// <summary> /// 发送一个GET请求 /// </summary> /// <param name="url"></param> /// <param name="headers"></param> /// <param name="cookie"></param> /// <returns></returns> public async static Task <HttpResults> Get(string url, IDictionary <string, string> headers = null) { try { HttpBaseProtocolFilter fiter = new HttpBaseProtocolFilter(); fiter.IgnorableServerCertificateErrors.Add(Windows.Security.Cryptography.Certificates.ChainValidationResult.Expired); using (var client = new HttpClient(fiter)) { if (headers != null) { foreach (var item in headers) { client.DefaultRequestHeaders.Add(item.Key, item.Value); } } var response = await client.GetAsync(new Uri(url)); if (!response.IsSuccessStatusCode) { return(new HttpResults() { code = (int)response.StatusCode, status = false, message = StatusCodeToMessage((int)response.StatusCode) }); } //response.EnsureSuccessStatusCode(); var buffer = await response.Content.ReadAsBufferAsync(); var byteArray = buffer.ToArray(); HttpResults httpResults = new HttpResults() { code = (int)response.StatusCode, status = response.StatusCode == HttpStatusCode.Ok, results = Encoding.UTF8.GetString(byteArray, 0, byteArray.Length), message = StatusCodeToMessage((int)response.StatusCode) }; return(httpResults); } } catch (Exception ex) { LogHelper.Log("GET请求失败" + url, LogType.ERROR, ex); return(new HttpResults() { code = ex.HResult, status = false, message = "网络请求出现错误(GET)" }); } }
/// <summary> /// 发送一个POST请求 /// </summary> /// <param name="url"></param> /// <param name="body"></param> /// <param name="headers"></param> /// <param name="cookie"></param> /// <param name="contentType"></param> /// <returns></returns> public async static Task <HttpResults> Post(string url, string body, IDictionary <string, string> headers = null, string contentType = "application/x-www-form-urlencoded") { try { using (var client = new HttpClient()) { if (headers != null) { foreach (var item in headers) { client.DefaultRequestHeaders.Add(item.Key, item.Value); } } var response = await client.PostAsync(new Uri(url), new HttpStringContent(body, Windows.Storage.Streams.UnicodeEncoding.Utf8, "application/x-www-form-urlencoded")); if (!response.IsSuccessStatusCode) { return(new HttpResults() { code = (int)response.StatusCode, status = false, message = StatusCodeToMessage((int)response.StatusCode) }); } var buffer = await response.Content.ReadAsBufferAsync(); var byteArray = buffer.ToArray(); HttpResults httpResults = new HttpResults() { code = (int)response.StatusCode, status = response.StatusCode == HttpStatusCode.Ok, results = Encoding.UTF8.GetString(byteArray), message = StatusCodeToMessage((int)response.StatusCode) }; return(httpResults); } } catch (Exception ex) { LogHelper.Log("POST请求失败" + url, LogType.ERROR, ex); return(new HttpResults() { code = ex.HResult, status = false, message = "网络请求出现错误(POST)" }); } }