2016-05-19 74 views
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); 
    } 
} 

回答

2

我相信有一種方法,但你失去了RestResponse的拉動數據,並自動反序列化的能力。我認爲使用情況更是從雲拉動斑點:

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屬性。

你必須選擇你想要的行爲。