C# 请求
/// <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; } }
await (await client.PostAsync(postUrl + urlPara, null)).Content.ReadAsStringAsync()
同步方法:
调用:
var content = new FormUrlEncodedContent(new[] { // body 为请求接口的参数名称,依据个人实际需求调整;参数依然为json对象 new KeyValuePair<string, string>("body", pushData) }); var result = RealNameSysAccessWebApiHelper.HttpPost(postUrl, content,null, "application/x-www-form-urlencoded");
/// <summary> /// 发起POST同步请求(Key Value) /// Method【application/json】【application/x-www-form-urlencoded】 /// 参数超长时使用此方法 /// </summary> /// <param name="content"></param> /// <param name="header"></param> /// <param name="contentType"></param> /// <returns></returns> public static string HttpPost(string url, FormUrlEncodedContent content, Dictionary<string,string> header = null, string contentType = "") { try { string resultContent = string.Empty; using (HttpClient client = new HttpClient()) { if (header != null) foreach (var item in header) { content.Headers.Add(item.Key, item.Value); } if (!string.IsNullOrEmpty(contentType)) { content.Headers.ContentType = new MediaTypeHeaderValue(contentType); } HttpResponseMessage response = client.PostAsync(url, content).Result; resultContent = response.Content.ReadAsStringAsync().Result; } return resultContent; } catch (Exception) { throw; } } /// <summary> /// 发起POST同步请求(Key Value) /// Method【application/json】【application/x-www-form-urlencoded】 /// 参数超长时使用此方法 /// </summary> /// <param name="content"></param> /// <param name="header"></param> /// <param name="contentType"></param> /// <returns></returns> public static string HttpPost(string url, FormUrlEncodedContent content, Dictionary<string,string> header = null, string contentType = "") { try { string resultContent = string.Empty; using (HttpClient client = new HttpClient()) { if (header != null) foreach (var item in header) { content.Headers.Add(item.Key, item.Value); } if (!string.IsNullOrEmpty(contentType)) { content.Headers.ContentType = new MediaTypeHeaderValue(contentType); } HttpResponseMessage response = client.PostAsync(url, content).Result; resultContent = response.Content.ReadAsStringAsync().Result; } return resultContent; } catch (Exception) { throw; } }
推送数据,返回信息:
/// <summary> /// Post HttpClient请求 /// 丁 /// </summary> /// <param name="url">webapi地址</param> /// <param name="postData">传输的的数据,格式:{"pass":""}</param> /// <returns></returns> public static string PostResponseNo(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 = httpClient.PostAsync(url, httpContent); var resultContent = response.Result.Content.ReadAsStringAsync().Result; return resultContent; } return string.Empty; } catch (Exception err) { string errMes = err.ToString(); throw new(errMes); } }
public static string PostDataByAuthHttpClient(string url, string postDataStr, string token, string strContentType = "application/json;charset=utf-8") { try { HttpContent httpContent = new StringContent(postDataStr); httpContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json") { CharSet = "utf-8" }; //httpContent.Headers.Add("Authorization", "Bearer " + token); //设置HttpClientHandler的AutomaticDecompression var handler = new HttpClientHandler() { AutomaticDecompression = DecompressionMethods.GZip }; using (HttpClient httpClient = new(handler)) { httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token); var response = httpClient.PostAsync(url, httpContent); var resultContent = response.Result.Content.ReadAsStringAsync().Result; return resultContent; } return string.Empty; } catch (Exception err) { string errMes = err.ToString(); throw new(errMes); } }
/// <summary> /// post 请求 /// </summary> /// <param name="strUrl"></param> /// <param name="content">参数</param> /// <returns></returns> public static string GetDataByPost(string strUrl, string content) { var uri = new Uri(strUrl); //创建路径 HttpWebRequest httpWeb = (HttpWebRequest)WebRequest.Create(uri); httpWeb.Timeout = 20000; httpWeb.Method = "POST"; httpWeb.ContentType = "application/json; charset=utf-8"; byte[] bytePara = Encoding.UTF8.GetBytes(content); using (Stream reqStream = httpWeb.GetRequestStream()) { //提交数据 reqStream.Write(bytePara, 0, bytePara.Length); } //获取服务器返回值 HttpWebResponse httpWebResponse = (HttpWebResponse)httpWeb.GetResponse(); Stream stream = httpWebResponse.GetResponseStream(); StreamReader streamReader = new StreamReader(stream, Encoding.GetEncoding("utf-8")); //获得返回值 string result = streamReader.ReadToEnd(); stream.Close(); return result; }
Headers 增加参数
/// <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("token", 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; } }