如何使用restsharp下载文件

How to use restsharp to download file

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

现在我的问题是我需要将此响应保存在服务器驱动器上的 xml 文件中。从那里我将把它插入数据库。并且需要使用使用 c# .net 4.5

的 http-client 或 rest-sharp 库的代码进行请求

对于上述情况,我不确定我应该怎么做。谁能给我一些建议

使用 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 似乎已停止。你可以试试这个

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

如果你想要异步版本

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

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

dotnet add package 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);
  }
}

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

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

从这里复制