代码如下所示:
protected string PostRequestAsync(string uri, dynamic payload, string ContentType = "application/json")
{
var result = "";
//处理Https
var handler = new HttpClientHandler();
handler.AllowAutoRedirect = true;
System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;
handler.ServerCertificateCustomValidationCallback = (sender, cert, chain, sslPolicyErrors) => { return true; };
//构建请求
using (var httpClient = new HttpClient(handler))
{
//20秒响应时间
httpClient.Timeout = new TimeSpan(0, 0, 0, 20);
HttpResponseMessage message = null;
try
{
//将请求payload序列化
var payloadString = JsonHelper.Serialize(payload);
HttpContent content = new StringContent(payloadString);
//httpClient.DefaultRequestHeaders.Add(HttpClientSession.TokenName, HttpClientSession.Token);
content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue(ContentType);
var plateformPostUrl = HttpClientSession.PlateformUrl+uri;
var response = httpClient.PostAsync(plateformPostUrl, content);
message = response.Result;
//如果返回码为200认为成功并返回结果
//如果Body内的code为500也认为成功,但要在业务中进行处理
if (message != null && message.StatusCode == System.Net.HttpStatusCode.OK)
{
result = message.Content.ReadAsStringAsync().Result;
}
else
{
throw new Exception($"code:{message.StatusCode},message:{message.Content.ReadAsStringAsync().Result}");
}
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
return result;
}
为什么会抛这个异常呀,这个方法是我在网上学到的
相应超时了吧
建议去掉 catch (Exception ex)
部分的代码可以看到更详细的错误信息
用await 等待异步执行完成
(A task was canceled) 你设置了 超时时间 20秒没响应 httprequest 自动取消了。。
我很好奇。调了什么接口 20秒 没结果。。。