Skip to content

Commit d2ce321

Browse files
authored
#147 Use SendAsync instead PostAsync to retrieve headers and detect server errors (#149)
* #147 Use SendAsync instead PostAsync to retrieve headers and detect server 500 errors * Improved tests performance by keeping connections open
1 parent 54628e1 commit d2ce321

File tree

2 files changed

+17
-3
lines changed

2 files changed

+17
-3
lines changed

MegaApiClient.Tests/Context/TestContext.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -66,7 +66,7 @@ public void ClearLogger()
6666
protected virtual IMegaApiClient CreateClient()
6767
{
6868
this.Options = new Options(applicationKey: "ewZQFBBC");
69-
this.WebClient = new TestWebClient(new WebClient(this.WebTimeout, null, new TestMessageHandler(this.logMessageAction), true), MaxRetry, this.logMessageAction);
69+
this.WebClient = new TestWebClient(new WebClient(this.WebTimeout, null, new TestMessageHandler(this.logMessageAction), false), MaxRetry, this.logMessageAction);
7070

7171
return new MegaApiClient(this.Options, this.WebClient);
7272
}

MegaApiClient/WebClient_HttpClient.cs

Lines changed: 16 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ namespace CG.Web.MegaApiClient
33
{
44
using System;
55
using System.IO;
6+
using System.Net;
67
using System.Reflection;
78
using System.Text;
89
using System.Threading;
@@ -55,8 +56,21 @@ private string PostRequest(Uri url, Stream dataStream, string contentType)
5556
using (StreamContent content = new StreamContent(dataStream, this.BufferSize))
5657
{
5758
content.Headers.ContentType = new MediaTypeHeaderValue(contentType);
58-
using (HttpResponseMessage response = this.httpClient.PostAsync(url, content).Result)
59+
60+
var requestMessage = new HttpRequestMessage(HttpMethod.Post, url);
61+
requestMessage.Content = content;
62+
63+
using (HttpResponseMessage response = this.httpClient.SendAsync(requestMessage, HttpCompletionOption.ResponseHeadersRead).Result)
5964
{
65+
if (!response.IsSuccessStatusCode
66+
&& response.StatusCode == HttpStatusCode.InternalServerError
67+
&& response.ReasonPhrase == "Server Too Busy")
68+
{
69+
return ((long)ApiResultCode.RequestFailedRetry).ToString();
70+
}
71+
72+
response.EnsureSuccessStatusCode();
73+
6074
using (Stream stream = response.Content.ReadAsStreamAsync().Result)
6175
{
6276
using (StreamReader streamReader = new StreamReader(stream, Encoding.UTF8))
@@ -75,4 +89,4 @@ private ProductInfoHeaderValue GenerateUserAgent()
7589
}
7690
}
7791
}
78-
#endif
92+
#endif

0 commit comments

Comments
 (0)