如何使用RestSharp下载文件。

49

我有一个URL(客户端实时反馈的URL),在浏览器中输入后会返回XML响应。我已将其保存在文本文件中,大小为8 MB。

现在我的问题是我需要将这个响应保存在服务器驱动器上的XML文件中。然后我将把它插入到数据库中,并使用C# .NET 4.5的http-client或rest-sharp库的代码发出请求。

对于上述情况,我不确定该怎么做。有人能给我建议吗?

5个回答

53

使用 RestSharp,它就在 readme 中:

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

使用HttpClient会涉及到更多细节。请看这篇博客文章

另一个选择是Flurl.Http(免责声明:我是作者)。它在幕后使用了HttpClient,提供了流畅的接口和许多方便的辅助方法,包括:

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

NuGet 上获取它。


1
方法 SaveAs 被移除了吗?我不能使用它。 可能我需要使用 File.WriteAllBytes(fileName, bytesArray); - JCarlosR
19
SaveAs方法仍然存在,位于RestSharp.Extensions命名空间的MiscExtensions类中。 - pushasha
更新的ReadMe链接:https://github.com/restsharp/RestSharp/blob/master/README.md - IbrarMumtaz
6
很遗憾,“DownloadData”没有异步版本。 - Mugen

26

看起来SaveAs已经停用了。你可以尝试这个。

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

3
请提供需要翻译的具体内容,以便我进行翻译。 - interesting-name-here
2
SaveAs仍然存在,您需要添加一个using语句:using RestSharp.Extensions; - C.J.
3
MiscExtensions.SaveAs在新版本中已经被标记为过时。 - morrow

19

如果您需要异步版本

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

请求在哪里定义? - MARKAND Bhatt
1
@MARKANDBhatt,我更新了答案,并加入了请求初始化。 - Vitaly
"'MiscExtensions.SaveAs(byte[], string)'已经过时:'此方法将很快被移除。如果您正在使用它,请将代码复制到您的项目中。" - Marc.2377
FYI ExecuteTaskAsync 也已经过时了。 - Marc.2377

7
不要在读取时将文件保存在内存中,直接将其写入磁盘。
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


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

dotnet add package RestSharp

使用Bearer身份验证
// 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);
  }
}

使用Bearer身份验证从响应中保存文件的完美逻辑。感谢节省时间。 - Aravindhan R
1
需要导入一堆额外的模块,使用这些函数也是很好的,而且IDE提示并非所有代码路径都返回值。 - Nikolay Advolodkin

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接