/// <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(); HttpResults httpResults = new HttpResults() { code = (int)response.StatusCode, status = response.StatusCode == HttpStatusCode.Ok, results = await response.Content.ReadAsStringAsync(), message = StatusCodeToMessage((int)response.StatusCode) }; return(httpResults); } } catch (Exception ex) { LogHelper.WriteLog("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) }); } string result = await response.Content.ReadAsStringAsync(); HttpResults httpResults = new HttpResults() { code = (int)response.StatusCode, status = response.StatusCode == HttpStatusCode.Ok, results = result, message = StatusCodeToMessage((int)response.StatusCode) }; return(httpResults); } } catch (Exception ex) { LogHelper.WriteLog("POST请求失败" + url, LogType.ERROR, ex); return(new HttpResults() { code = ex.HResult, status = false, message = "网络请求出现错误(POST)" }); } }