C# HttpClient发送Get和Post请求

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

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

你可能感兴趣的:(C# HttpClient发送Get和Post请求)