1
我們正在使用RestSharp v105.2.3。限制在RestSharp中下載大小
有沒有辦法在接收到N個字節後停止接收響應,其中N是我可以控制的參數?
編輯:這是我的完整解決方案,基於Berin的答案。
public static class IRestClientExtensions
{
public static IRestResponse Execute(this IRestClient client, IRestRequest request, byte[] buffer, out int bufferSize)
{
var totalBytesRead = 0;
request.ResponseWriter = stream =>
{
while (totalBytesRead < buffer.Length)
{
var bytesRead = stream.Read(buffer, totalBytesRead, buffer.Length - totalBytesRead);
if (bytesRead == 0)
{
break;
}
totalBytesRead += bytesRead;
}
};
var response = client.Execute(request);
bufferSize = totalBytesRead;
return response;
}
}
單元測試(使用NUnit):
[TestFixture]
public class IRestClientExtensionsTests
{
[Test, Explicit]
public void Execute_OutputBufferTooSmall()
{
var client = new RestClient("https://www.w3.org/TR/html4/charset.html");
var request = new RestRequest();
var buffer = new byte[4 * 1024];
int bufferSize;
var response = client.Execute(request, buffer, out bufferSize);
Assert.AreEqual(HttpStatusCode.OK, response.StatusCode);
Assert.IsTrue(string.IsNullOrEmpty(response.Content));
Assert.AreEqual(buffer.Length, bufferSize);
}
[Test, Explicit]
public void Execute_OutputBufferLargeEnough()
{
var client = new RestClient("https://www.w3.org/TR/html4/charset.html");
var request = new RestRequest();
var buffer = new byte[256 * 1024];
int bufferSize;
var response = client.Execute(request, buffer, out bufferSize);
Assert.AreEqual(HttpStatusCode.OK, response.StatusCode);
Assert.IsTrue(string.IsNullOrEmpty(response.Content));
Assert.IsTrue(bufferSize < buffer.Length);
}
}