c# 调用webapi的几种方式
HttpHelper帮助类
public static class Httphelper { // Post请求 public static string PostResponse(string url, string postData, out string statusCode) { string result = string.Empty; //设置Http的正文 HttpContent httpContent = new StringContent(postData); //设置Http的内容标头 httpContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json"); //设置Http的内容标头的字符 httpContent.Headers.ContentType.CharSet = "utf-8"; using (HttpClient httpClient = new HttpClient()) { //异步Post HttpResponseMessage response = httpClient.PostAsync(url, httpContent).Result; //输出Http响应状态码 statusCode = response.StatusCode.ToString(); //确保Http响应成功 if (response.IsSuccessStatusCode) { //异步读取json result = response.Content.ReadAsStringAsync().Result; } } return result; } // 泛型:Post请求 public static T PostResponse<T>(string url, string postData) where T : class, new() { T result = default(T); HttpContent httpContent = new StringContent(postData); httpContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json"); httpContent.Headers.ContentType.CharSet = "utf-8"; using (HttpClient httpClient = new HttpClient()) { HttpResponseMessage response = httpClient.PostAsync(url, httpContent).Result; if (response.IsSuccessStatusCode) { Task<string> t = response.Content.ReadAsStringAsync(); string s = t.Result; //Newtonsoft.Json string json = JsonConvert.DeserializeObject(s).ToString(); result = JsonConvert.DeserializeObject<T>(json); } } return result; } // 泛型:Get请求 public static T GetResponse<T>(string url) where T : class, new() { T result = default(T); using (HttpClient httpClient = new HttpClient()) { httpClient.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json")); HttpResponseMessage response = httpClient.GetAsync(url).Result; if (response.IsSuccessStatusCode) { Task<string> t = response.Content.ReadAsStringAsync(); string s = t.Result; string json = JsonConvert.DeserializeObject(s).ToString(); result = JsonConvert.DeserializeObject<T>(json); } } return result; } // Get请求 public static string GetResponse(string url, out string statusCode) { string result = string.Empty; using (HttpClient httpClient = new HttpClient()) { httpClient.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json")); HttpResponseMessage response = httpClient.GetAsync(url).Result; statusCode = response.StatusCode.ToString(); if (response.IsSuccessStatusCode) { result = response.Content.ReadAsStringAsync().Result; } } return result; } // Put请求 public static string PutResponse(string url, string putData, out string statusCode) { string result = string.Empty; HttpContent httpContent = new StringContent(putData); httpContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json"); httpContent.Headers.ContentType.CharSet = "utf-8"; using (HttpClient httpClient = new HttpClient()) { HttpResponseMessage response = httpClient.PutAsync(url, httpContent).Result; statusCode = response.StatusCode.ToString(); if (response.IsSuccessStatusCode) { result = response.Content.ReadAsStringAsync().Result; } } return result; } // 泛型:Put请求 public static T PutResponse<T>(string url, string putData) where T : class, new() { T result = default(T); HttpContent httpContent = new StringContent(putData); httpContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json"); httpContent.Headers.ContentType.CharSet = "utf-8"; using (HttpClient httpClient = new HttpClient()) { HttpResponseMessage response = httpClient.PutAsync(url, httpContent).Result; if (response.IsSuccessStatusCode) { Task<string> t = response.Content.ReadAsStringAsync(); string s = t.Result; string json = JsonConvert.DeserializeObject(s).ToString(); result = JsonConvert.DeserializeObject<T>(json); } } return result; } }
主要是Post传参的三种方式
//方法一,传json参数 var d = new { username = " ", password = " ", grant_type = "", appcode = " ", companyid = " ", version = "1.0", }; var data = JsonConvert.SerializeObject(d); HttpContent httpContent = new StringContent(data);
或
var data= "{\"username\":\"" + username+ "\",\"password\": \"" + password + "\",\"grant_type\": \"" + grant_type+ "\",\"version\": \"" + version+ "\"}";
//方法二,传表单参数 FormUrlEncodedContent formContent = new FormUrlEncodedContent(new Dictionary<string, string>() { {"username"," " }, {"password"," " }, {"grant_type","" }, {"appcode"," " }, {"companyid"," " }, {"version","1.0" }, });
//方法三,传字节流 string postparas = @"{ ""username"":"" "",""password"":"" "",""grant_type"":"""",""appcode"":"" "",""companyid"":"" "",""version"":""1.0""}"; using (Stream dataStream = new MemoryStream(Encoding.Unicode.GetBytes(postparas) ?? new byte[0])) { using (HttpContent content = new StreamContent(dataStream)) { } }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义