您的位置:首页 > 理论基础 > 计算机网络

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;
}

仅供学习参考,如有侵权联系我删除

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: