/// <summary> /// Get请求 /// </summary> /// <param name="url">webapi地址</param> /// <param name="accessToken">accessToken</param> /// <returns></returns> public static string GetRequest(string url, string accessToken) { try { Uri uri = new Uri(url); HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri); request.Headers.Add("Authorization", "Bearer " + accessToken); request.PreAuthenticate = true; //request配置请查看页面的开发者工具,尽量保证与request headers相同 request.Method = "GET";//或者GET byte[] bytes = Encoding.UTF8.GetBytes(""); HttpWebResponse response = (HttpWebResponse)request.GetResponse(); StreamReader myStreamReader = new StreamReader(response.GetResponseStream(), Encoding.UTF8); string retString = myStreamReader.ReadToEnd(); myStreamReader.Close(); if (response != null) { response.Close(); } if (request != null) { request.Abort(); } return retString; } catch (Exception err) { string errMes = err.ToString(); throw new(errMes); } } /// <summary> /// Post请求 /// </summary> /// <param name="url">webapi地址</param> /// <param name="postData">传输的的数据,格式:{"pass":""}</param> /// <returns></returns> public static async Task<string> PostResponse(string url, string postData) { try { HttpContent httpContent = new StringContent(postData); httpContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json") { CharSet = "utf-8" }; //设置HttpClientHandler的AutomaticDecompression var handler = new HttpClientHandler() { AutomaticDecompression = DecompressionMethods.GZip }; using (HttpClient httpClient = new(handler)) { var response = await httpClient.PostAsync(url, httpContent); if (response.IsSuccessStatusCode) { string result = await response.Content.ReadAsStringAsync(); return result; } } return string.Empty; } catch (Exception err) { string errMes = err.ToString(); throw new(errMes); } } /// <summary> /// Http Post 需要 token 请求 /// </summary> /// <param name="url"></param> /// <param name="postDataStr"></param> /// <param name="token"></param> /// <returns></returns> public static string PostDataByAuth(string url, string postDataStr, string token) { try { string result = string.Empty; // 构造请求 HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest; request.Method = "POST"; request.ContentType = "application/json"; request.Headers.Add("Authorization", "Bearer " + token); // 写入数据主体 using (var writer = new StreamWriter(request.GetRequestStream())) { writer.Write(postDataStr); } // 获取响应 using (var response = request.GetResponse()) { var stremReader = new StreamReader(response.GetResponseStream()); result = stremReader.ReadToEnd(); } return result; } catch (Exception ex) { return ex.Message; } }