这里简要介绍async await异步编程用法。
以HttpClient的PostAsync举例,异步调用Http POST请求。
public async Task<string> PostAsync(string url, string strJson)//post异步请求方法
{
try
{
HttpContent content = new StringContent(strJson);
content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");
//由HttpClient发出异步Post请求
HttpResponseMessage res = await client.PostAsync(url, content);
if (res.StatusCode == System.Net.HttpStatusCode.OK)
{
Thread.Sleep(1000);//线程睡眠1秒用于测试
string str = res.Content.ReadAsStringAsync().Result;
return str;
}
else
return null;
}
catch (Exception ex)
{
return null;
}
}
编写调用方式:
再编写一个异步方法,用来获取异步POST返回的信息,并进行一些操作。
/// <summary>
/// 再编写一个异步方法,用来获取异步POST返回的信息,并进行一些操作。
/// </summary>
/// <param name="url">POST请求地址</param>
/// <param name="strJson">POST请求的json字符串参数</param>
/// <returns></returns>
private async Task<string> GetContentAsync(string url, string strJson)
{
HttpClientHelper cl = new HttpClientHelper();
var content = await cl.PostAsync(url, strJson);
textBox6.Text = content;
return content;
}
测试实例:
private void button19_Click(object sender, EventArgs e)
{
InputText();
jsonStuInfo stuInfo = new jsonStuInfo();
stuInfo.sTID = this.sTID;
stuInfo.nChildTID = this.nChildTID;
string url = this.address + "Api_TestProc_Paper_GetPaperInfo";
string strJson = JsonConvert.SerializeObject(stuInfo);
var zipTeaInfo = GetContentAsync(url, strJson);
textBox6.Text = zipTeaInfo.IsCompleted.ToString();
}
此处返回信息经过加密,并非乱码。