簡體   English   中英

使用 HttpClient 處理響應值

[英]Handling response values using HttpClient

我正在實現一項服務,該服務使 API 使用HttpClient調用外部服務。 特別是其中一個調用並不總是返回與預期相同的答案。 實際上:

這是我的電話:

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

這是方面響應體 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
}

其中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參數為空。

有一種方法可以管理調用以返回響應的 object 但僅在status參數successfull時才返回? 謝謝

一些 api 采用wait=1參數或類似於等待的參數。 否則,您必須輪詢(可能是不同的網址)。

詳細信息應從您的 API 文檔中獲得。

按照建議,解決了輪詢請求:(客戶端在 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