C# HttpClient发送Get和Post请求
2020-05-26 13:43
93 查看
C# HttpClient发送Get和Post请求
C#.NET命名空间System.Net.Http下的HttpClient可以发送Post/Get请求调用API,也是写过多次但真要自己写起来还要花时间调试,记个笔记。
Post请求
[HttpPost] public async Task<JsonResult> GetWhiteList(string recruitmentPlanId, string kAccount, int pageSize, int pageIndex) { RecruitmentPaginationModel model = new RecruitmentPaginationModel(); try { queryModel qm = new queryModel(); qm.recruitmentPlanId = recruitmentPlanId; qm.kAccount = kAccount; qm.pageSize = pageSize; qm.pageIndex = pageIndex; using (var client = new HttpClient()) { client.DefaultRequestHeaders.Accept.TryParseAdd("application/json"); HttpContent content = new StringContent(JsonConvert.SerializeObject(qm)); content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json"); //由HttpClient发出异步Post请求 HttpResponseMessage res = await client.PostAsync("http://localhost:63657/api/Recruitment/GetWhiteList", content); if (res.StatusCode == System.Net.HttpStatusCode.OK) { string jsonStr = res.Content.ReadAsStringAsync().Result; model = JsonConvert.DeserializeObject<RecruitmentPaginationModel>(jsonStr); return Json(new { total = model.pageSize, rows = model.listModel }); } else return null; } } catch (Exception ex) { return null; } }
Get请求
[HttpPost] public string AddWhiteList(string recruitmentPlanId, string kAccount) { string result = "false"; using (var client = new HttpClient()) { client.DefaultRequestHeaders.Accept.TryParseAdd("application/json"); HttpResponseMessage res = client.GetAsync(string.Format("http://localhost:63657/api/Recruitment/AddWhiteList?recruitmentPlanId={0}&kAccount={1}", recruitmentPlanId, kAccount)).Result; if (res.StatusCode == System.Net.HttpStatusCode.OK) { result = res.Content.ReadAsStringAsync().Result; } } return result; }
仅供学习参考,如有侵权联系我删除
相关文章推荐
- java apache commons HttpClient发送get和post请求的学习整理
- C#模拟http 发送post或get请求的简单实例
- HttpClient 发送Post Get请求例子(包含设置请求头信息和获取返回头信息)
- android_30_使用HttpClient发送Get和Post请求
- C#代码模拟http发送get和post请求
- C#模拟http 发送post或get请求
- java httpclient发送post get 请求
- java 发送http get post 请求,以及java通过httpclient中转上传文件
- [Socket]利用Android下的HttpClient发送GET && POST请求
- httpclient发送post/get请求,Java后台怎么接受
- C#模拟http 发送post或get请求
- HttpClient发送Get和Post请求
- httpclient发送GET和POST请求方式的具体步骤
- C#模拟http 发送post或get请求
- 利用HttpClient发送Get和Post请求
- HttpClient发送get请求,post请求代码
- java apache commons HttpClient发送get和post请求的学习整理
- C# Get和Post获取和请求页面信息(HttpWebRequest 、WebClient、HttpClient)
- android内置的HttpClient发送get、post请求用法
- HttpClient发送get post请求和数据解析