我有一个URL(来自客户端的实时源的URL),当我在浏览器中点击时返回xml响应。我已将其保存在文本文件中,其大小为8 MB。
现在我的问题是我需要将此响应保存在服务器驱动器上的xml文件中。从那里我将在数据库中插入此。并且需要使用http-client或c#.net 4.5
的rest-sharp库使用代码进行请求我不确定我应该为上述情况做些什么。任何身体都可以向我推荐一些东西
答案 0 :(得分:29)
使用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。
答案 1 :(得分:7)
看来SaveAs已经停产。你可以试试这个
var client = new RestClient("http://example.com")
byte[] response = client.DownloadData(request);
File.WriteAllBytes(SAVE_PATH, response);
答案 2 :(得分:3)
阅读时不要将文件保存在内存中。直接写入磁盘。
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);
答案 3 :(得分:2)
如果您需要异步版本
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);
答案 4 :(得分:2)
将以下NuGet软件包添加到当前系统中
dotnet添加软件包RestSharp
使用承载身份验证
int index = 0;
foreach (string[] item in dataList)
{
for (int i = 0; i < item.Length; i++)
{
Console.WriteLine("Column {0} details: {1}", index+1, item[i]);
}
index++;
}
使用基本身份验证
// 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);
}
}