【发布时间】:2021-04-09 15:19:06
【问题描述】:
我正在实现一个使用HttpClient 对外部服务进行API 调用的服务。
特别是其中一个调用并不总是返回与预期相同的答案。实际:
这是我的电话:
using (HttpClientHandler handler = new HttpClientHandler { Credentials = new NetworkCredential(key, "") })
using (HttpClient client = new HttpClient(handler))
{
client.Timeout = TimeSpan.FromMilliseconds(Timeout.Infinite);
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, url);
using (HttpResponseMessage response = await client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead))
{
using (Stream body = await response.Content.ReadAsStreamAsync())
{
using (StreamReader reader = new StreamReader(body))
{
string read = string.Empty;
while (!reader.EndOfStream)
{
read += reader.ReadLine();
}
return JsonObject.Parse(read);
}
}
}
这是方面的响应主体对象:
{
"id" : 15,
"key" : "API_KEY",
"status" : "successful",
"sandbox" : true,
"created_at" : "2013-10-27T13:41:00Z",
"finished_at" : "2013-10-27T13:41:13Z",
"source_file" : {"id":2,"name":"testfile.pdf","size":90571},
"target_files" : [{"id":3,"name":"testfile.pptx","size":15311}],
"target_format" : "png",
"credit_cost" : 1
}
其中status 参数为successful,target_files 参数为array of objects。
然而,有时,答案基本上是说它还没有完成转换(这个 API 是一个文件转换服务),具有这种类型的主体:
{
"id" : 15,
"key" : "API_KEY",
"status" : "converting",
"sandbox" : true,
"created_at" : "2013-10-27T13:41:00Z",
"finished_at" : "2013-10-27T13:41:13Z",
"source_file" : {"id":2,"name":"testfile.pdf","size":90571},
"target_files" : [{}],
"target_format" : "png",
"credit_cost" : 0
}
其中status 参数为converting,target_files 参数为空。
有一种方法可以管理调用以返回响应的对象,但仅当status 参数为successfull 时?谢谢
【问题讨论】:
标签: c# asp.net-mvc dotnet-httpclient api-management