feat: 优化反序列化响应的判断逻辑

This commit is contained in:
Fu Diwei
2021-12-09 00:28:40 +08:00
parent f9eba5ff05
commit b50c216fab
6 changed files with 48 additions and 44 deletions

View File

@@ -1,8 +1,8 @@
using System;
using System.Collections.ObjectModel;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Flurl.Http;
@@ -121,14 +121,13 @@ namespace SKIT.FlurlHttpClient.Wechat.Ads
private async Task<T> GetResposneAsync<T>(IFlurlResponse flurlResponse)
where T : WechatAdsResponse, new()
{
string contentType = flurlResponse.Headers.GetAll("Content-Type").FirstOrDefault() ?? string.Empty;
string contentDisposition = flurlResponse.Headers.GetAll("Content-Disposition").FirstOrDefault() ?? string.Empty;
bool contentTypeIsNotJson =
(flurlResponse.StatusCode != (int)HttpStatusCode.OK) ||
(!contentType.StartsWith("application/json") && !contentType.StartsWith("text/json")) ||
(contentDisposition.StartsWith("attachment"));
byte[] bytes = await flurlResponse.GetBytesAsync().ConfigureAwait(false);
bool jsonable = bytes.Length > 1 &&
(bytes[0] == 91 && bytes[bytes.Length - 1] == 93) || // "[...]"
(bytes[0] == 123 && bytes[bytes.Length - 1] == 125); // "{...}"
T result = jsonable ? JsonSerializer.Deserialize<T>(Encoding.UTF8.GetString(bytes)) : new T();
T result = contentTypeIsNotJson ? new T() : await flurlResponse.GetJsonAsync<T>().ConfigureAwait(false);
result.RawStatus = flurlResponse.StatusCode;
result.RawHeaders = new ReadOnlyDictionary<string, string>(
flurlResponse.Headers
@@ -138,7 +137,8 @@ namespace SKIT.FlurlHttpClient.Wechat.Ads
v => string.Join(", ", v.Select(e => e.Value))
)
);
result.RawBytes = await flurlResponse.ResponseMessage.Content.ReadAsByteArrayAsync().ConfigureAwait(false);
result.RawBytes = bytes;
return result;
}
}