【问题标题】:How to use restsharp to download file如何使用restsharp下载文件
【发布时间】:2015-03-18 13:24:19
【问题描述】:

我有一个 URL(来自客户端的实时供稿的 URL),当我在浏览器中点击它时会返回 xml 响应。我已将其保存在文本文件中,大小为 8 MB。

现在我的问题是我需要将此响应保存在服务器驱动器上的 xml 文件中。从那里我将把它插入数据库。并且需要使用 c# .net 4.5 的 http-client 或 rest-sharp 库的代码发出请求

我不确定我应该如何处理上述情况。任何人都可以给我一些建议吗

【问题讨论】:

    标签: c# asp.net xml httpclient restsharp


    【解决方案1】:

    有了 RestSharp,它就在readme

    var client = new RestClient("http://example.com");
    client.DownloadData(request).SaveAs(path);
    

    HttpClient 的参与度更高。看看this blog post

    另一个选项是Flurl.Http(免责声明:我是作者)。它在底层使用HttpClient,并提供了流畅的界面和许多方便的辅助方法,包括:

    await "http://example.com".DownloadFileAsync(folderPath, "foo.xml");
    

    通过NuGet获取它。

    【讨论】:

    • 方法SaveAs被删除了?我不能用它。可能我必须使用File.WriteAllBytes(fileName, bytesArray);
    • @JCarlos :SaveAs 方法仍然存在。它位于RestSharp.Extensions 命名空间MiscExtensions 类中。
    • 太糟糕了DownloadData 没有异步版本
    【解决方案2】:

    SaveAs 似乎已停止使用。你可以试试这个

    var client = new RestClient("http://example.com")    
    byte[] response = client.DownloadData(request);
    File.WriteAllBytes(SAVE_PATH, response);
    

    【讨论】:

    • 请参阅上述答案中的评论。
    • SaveAs 还在,要加一条 using 语句:using RestSharp.Extensions;
    • MiscExtensions.SaveAs 在较新的版本中已被标记为过时。
    【解决方案3】:

    如果你想要异步版本

    var request = new RestRequest("/resource/5", Method.GET);
    var client = new RestClient("http://example.com");
    var response = await client.ExecuteTaskAsync(request);
    if (response.StatusCode != HttpStatusCode.OK)
        throw new Exception($"Unable to download file");
    response.RawBytes.SaveAs(path);
    

    【讨论】:

    • 请求在哪里定义?
    • @MARKANDBhatt,我用请求初始化更新了答案
    • "'MiscExtensions.SaveAs(byte[], string)' is obsolete: '这个方法很快就会被移除。如果你使用它,请将代码复制到你的项目中。"
    • 仅供参考 ExecuteTaskAsync 也已过时。
    【解决方案4】:

    读取时不要将文件保存在内存中。直接写入磁盘。

    var tempFile = Path.GetTempFileName();
    using var writer = File.OpenWrite(tempFile);
    
    var client = new RestClient(baseUrl);
    var request = new RestRequest("Assets/LargeFile.7z");
    request.ResponseWriter = responseStream =>
    {
        using (responseStream)
        {
            responseStream.CopyTo(writer);
        }
    };
    var response = client.DownloadData(request);
    

    从这里复制https://stackoverflow.com/a/59720610/179017

    【讨论】:

      【解决方案5】:

      在当前系统中添加如下 NuGet 包

      dotnet 添加包 RestSharp

      使用承载认证

      // Download file from 3rd party API
      [HttpGet("[action]")]
      public async Task<IActionResult> Download([FromQuery] string fileUri)
      {
        // Using rest sharp 
        RestClient client = new RestClient(fileUri);
        client.ClearHandlers();
        client.AddHandler("*", () => { return new JsonDeserializer(); });
        RestRequest request = new RestRequest(Method.GET);
        request.AddParameter("Authorization", string.Format("Bearer " + accessToken), 
        ParameterType.HttpHeader);
        IRestResponse response = await client.ExecuteTaskAsync(request);
        if (response.StatusCode == System.Net.HttpStatusCode.OK)
        {
          // Read bytes
          byte[] fileBytes = response.RawBytes;
          var headervalue = response.Headers.FirstOrDefault(x => x.Name == "Content-Disposition")?.Value;
          string contentDispositionString = Convert.ToString(headervalue);
          ContentDisposition contentDisposition = new ContentDisposition(contentDispositionString);
          string fileName = contentDisposition.FileName;
          // you can write a own logic for download file on SFTP,Local local system location
          //
          // If you to return file object then you can use below code
          return File(fileBytes, "application/octet-stream", fileName);
        }
      }
      

      使用基本身份验证

      // Download file from 3rd party API
      [HttpGet("[action]")]
      public async Task<IActionResult> Download([FromQuery] string fileUri)
      { 
        RestClient client = new RestClient(fileUri)
          {
             Authenticator = new HttpBasicAuthenticator("your user name", "your password")
          };
        client.ClearHandlers();
        client.AddHandler("*", () => { return new JsonDeserializer(); });
        RestRequest request = new RestRequest(Method.GET);  
        IRestResponse response = await client.ExecuteTaskAsync(request);
        if (response.StatusCode == System.Net.HttpStatusCode.OK)
        {
          // Read bytes
          byte[] fileBytes = response.RawBytes;
          var headervalue = response.Headers.FirstOrDefault(x => x.Name == "Content-Disposition")?.Value;
          string contentDispositionString = Convert.ToString(headervalue);
          ContentDisposition contentDisposition = new ContentDisposition(contentDispositionString);
          string fileName = contentDisposition.FileName;
          // you can write a own logic for download file on SFTP,Local local system location
          //
          // If you to return file object then you can use below code
          return File(fileBytes, "application/octet-stream", fileName);
        }
      }
      

      【讨论】:

      • 使用承载身份验证从响应中保存文件的完美逻辑。感谢您节省时间。
      • 需要一堆额外的导入,这些函数的使用也很好,IDE说不是所有的代码路径都返回一个值
      猜你喜欢
      • 1970-01-01
      • 2021-04-26
      • 1970-01-01
      • 2018-04-16
      • 1970-01-01
      • 1970-01-01
      • 2016-11-27
      • 2015-02-07
      相关资源
      最近更新 更多