我看到了很多关于这个问题的提问,所有的指向都告诉我需要使用ConfigureAwait(false),但即使这样做了,它仍然没有返回任何响应。当我运行调试器时,代码停留在PostAsync处,不继续执行我的代码。这里我做错了什么吗?这和我通过HTTPS调用API有关吗?
这是代码:
这是代码:
public async static Task<PaymentModel> AddAsync(Card card)
{
HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", Convert.ToBase64String(ASCIIEncoding.ASCII.GetBytes(string.Format("{0}:", "hidden"))));
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;
var cardJson = JsonConvert.SerializeObject(card);
var postRequest = new StringContent(cardJson, Encoding.UTF8, "application/json");
var request = await client.PostAsync(new Uri("https://sample-3rd-party-api/api/endpoint/here"), postRequest).ConfigureAwait(false);
var content = await request.Content.ReadAsStringAsync().ConfigureAwait(false);
}
编辑:
针对下面的评论,该代码是从一个名为AddAsync(Card card)的方法中调用的,该方法在点击带有处理程序的按钮时被调用:
public async void OnExecute(object sender, EventArgs args)
{
//some code here
payment = await PaymentModel.AddAsync(card).ConfigureAwait(false);
}
编辑2:我尝试使用ping API,但它返回请求超时,但是当我使用Postman尝试时,它运行良好(该API只是一个开放给所有人的沙盒,所以分享这个):
编辑3:
我认为问题出在我没有SSL证书来访问API。我有一个连接到同一个API的PHP服务器,我必须将SSL_VERIFYPEER设置为false才能访问它(不用担心,我现在添加了一个cacert,所以它又变成了true)。这里会发生相同的问题吗?如果是这样,我该如何为我的Xamarin Forms应用程序创建有效证书?
Timeout
超时时,HttpClient
会抛出TaskCanceledException
异常。你确定第三方API正在工作吗? - Cheng Chen