使用 HttpClient 处理响应值

Handling response values using HttpClient

我正在实施一项服务,该服务使用 HttpClient 对外部服务进行 API 调用。 特别是其中一个调用并不总是 return 预期的相同答案。实际上:

这是我的电话:

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 参数是 successfultarget_files 参数是 array of objects

不过有时回复基本上是还没转换完(这个API是一个文件转换服务),body是这样的:

{
    "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参数为convertingtarget_files参数为空。

有一种方法可以管理调用以便 return 响应的对象但仅当 status 参数为 successfull 时?谢谢

一些 api 使用 wait=1 参数或类似的东西来等待。否则,您将不得不 poll(可能是不同的 url)。

详细信息应该可以从您的 API 文档中获得。

按照建议,解决了轮询请求: (客户端在范围级别实例化)

for (int attempt = 0; attempt < maxAttempts; attempt++)
{
    using (HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, url))
    {
        TimeSpan delay = default;
        using (HttpResponseMessage response = await _client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead).ConfigureAwait(false))
        {
            if (response.IsSuccessStatusCode)
            {
                using (HttpContent content = response.Content)
                {
                    string data = await content.ReadAsStringAsync().ConfigureAwait(false);
                    JsonValue value = JsonObject.Parse(data);
                    JsonValue status = value["status"] ?? string.Empty;
                    string statusString = status != null ? (string)status : string.Empty;

                    if (!string.IsNullOrEmpty(status) && statusString.Equals("successful", StringComparison.InvariantCultureIgnoreCase))
                        return value;
                }
            }

            delay = response.Headers.RetryAfter?.Delta ?? TimeSpan.FromSeconds(3);
        }

        await Task.Delay(delay);
    }
}