简体   繁体   English

使用 HttpClient 处理响应值

[英]Handling response values using HttpClient

I'm implementing a service that makes API calls to an external service using HttpClient .我正在实现一项服务,该服务使 API 使用HttpClient调用外部服务。 One of these calls in particular does not always return the same answer that is expected.特别是其中一个调用并不总是返回与预期相同的答案。 Pratically:实际上:

this is my call:这是我的电话:

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);
            }
        }
    }

this is the aspected response body object:这是方面响应体 object:

{
    "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
}

where the status parameter is successful and the target_files parameter is an array of objects .其中status参数是successful的,而target_files参数是一个array of objects

Sometimes however, the answer basically comes back saying that it hasn't finished converting yet (this API is a files conversion service), with this type of body:然而,有时,答案基本上回来说它还没有完成转换(这个 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
}

where the status parameter is converting and the target_files parameter is empty.其中status参数正在converting并且target_files参数为空。

There is a way to manage the call in order to return the object of the response but only when the status parameter is successfull ?有一种方法可以管理调用以返回响应的 object 但仅在status参数successfull时才返回? Thanks谢谢

Some apis take a wait=1 parameter or something similar to wait.一些 api 采用wait=1参数或类似于等待的参数。 Otherwise, you'd have to poll (likely a different url).否则,您必须轮询(可能是不同的网址)。

Details should be available from your API documentation.详细信息应从您的 API 文档中获得。

As suggested, solved polling the request: (the client is instantiated at the scope level)按照建议,解决了轮询请求:(客户端在 scope 级别实例化)

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);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM