簡體   English   中英

如何使用restsharp下載文件

[英]How to use restsharp to download file

我有一個 URL(來自客戶端的實時提要的 URL),當我在瀏覽器中點擊它時會返回 xml 響應。 我已將其保存在文本文件中,它的大小為 8 MB。

現在我的問題是我需要將此響應保存在服務器驅動器上的 xml 文件中。 從那里我將把它插入到數據庫中。 並且需要使用代碼使用 c# .net 4.5 的 http-client 或 rest-sharp 庫進行請求

我不確定我應該為上述案例做什么。 任何機構都可以給我建議嗎

使用 RestSharp,它就在自述文件中

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

使用HttpClient ,則涉及更多。 看看這篇博文

另一種選擇是Flurl.Http (免責聲明:我是作者)。 它在HttpClient使用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);

閱讀時不要將文件保存在內存中。 直接寫入磁盤。

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

將以下 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);
  }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM