如何编写对API的异步获取请求

时间:2019-02-18 22:59:54

标签: c# rest

我已获得API的访问权限,并且我有多个文件要发送到API进行分析。响应以json格式保存在我的硬盘上,我希望它们以不同的文件名保存。

我想每3秒发送一个文件,以免崩溃。我知道如何为单个文件执行此操作,但不知道如何针对许多文件自动执行此操作。

我上传了以下名称的音频文件:www.xyz.com/myaudiofile1,www.xyz.com/myaudiofile2、www.xyz.com/myaudiofile3。

我正在使用Visual Studio,而我的唯一请求是:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net.Http;
using System.IO;
using RestSharp;
using RestSharp.Authenticators;

namespace TestAudio
{
    class Program
    {
        static void Main(string[] args)
        {  try
            {
                var ClientEndpoint = "https://website ";
    var audiofile = "https://myaudiofile1 ";
    var client = new RestClient(ClientEndpoint + audiofile);
    var request = new RestRequest(Method.GET);
    request.AddHeader("cache-control", "no-cache");
    request.AddHeader("Login", "Login Key");
    IRestResponse response = client.Execute(request);
    System.IO.File.WriteAllText(@"C:\Users\myaudiofile1.json",response.Content);
    Console.WriteLine(response.Content.ToString());
    Console.ReadLine();
}
catch (Exception ex)
{
    Console.WriteLine(ex.ToString());
}

}

1 个答案:

答案 0 :(得分:0)

如果您使用Microsoft的Reactive Framework(又名Rx),则可以执行以下操作:

var files = new[] { "myaudiofile1", "myaudiofile2", "myaudiofile3" };

var query =
    Observable
        .Timer(TimeSpan.Zero, TimeSpan.FromSeconds(3.0))
        .Zip(files, (_, audiofile) => audiofile)
        .Select(audiofile =>
        {
            var ClientEndpoint = "https://website ";
            var client = new RestClient(ClientEndpoint + audiofile);
            var request = new RestRequest(Method.GET);
            request.AddHeader("cache-control", "no-cache");
            request.AddHeader("Login", "Login Key");
            IRestResponse response = client.Execute(request);
            return (audiofile, response.Content);
        });

var subscription =
    query
        .Subscribe(x => System.IO.File.WriteAllText($@"C:\Users\{x.audiofile}.json", x.Content));

了解哪些对象是可丢弃的,这将很有用,因为这将改变我编写此代码的方式。

只需NuGet System.Reactive并添加using System.Reactive.Linq;即可使其正常工作。