我们正在使用RestSharp v105.2.3。
有没有办法在收到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);
}
}
答案 0 :(得分:2)
我相信有一种方法,但是你放弃了RestResponse
拉取数据并自动反序列化的能力。我相信用例更多的是从云中提取Blob:
var client = new RestClient("http://example.com");
var request = new RestRequest("resource/{id}", Method.POST);
request.ResponseWriter = (stream) => {
// work with the writer you recieve here.
// This is an Action<Stream> callback
};
// NOTE: the callback is invoked during this statement:
IRestResponse response = client.Execute(request);
// The response has all the meta information, but none of the data.
ResponseWriter
属性是Action<Stream>
回调。读取HTTP响应的代码如果提供了它,则调用ResponseWriter
,或者一次读取所有字节并填充Response.RawBytes
属性。
您必须选择所需的行为。