|
| 1 | +using Newtonsoft.Json; |
| 2 | +using JsonSerializer = Newtonsoft.Json.JsonSerializer; |
| 3 | + |
| 4 | +// ReSharper disable once CheckNamespace |
| 5 | +namespace System; |
| 6 | + |
| 7 | +static class HttpClientExtensions |
| 8 | +{ |
| 9 | + static async Task<T?> SendAsync<T>( |
| 10 | + this HttpClient client, |
| 11 | + ILogger logger, |
| 12 | + JsonSerializer? jsonSerializer, |
| 13 | + bool isCheckHttpUrl, |
| 14 | + string? requestUri, |
| 15 | + Func<HttpRequestMessage> requestFactory, |
| 16 | + string? accept, |
| 17 | + //bool enableForward, |
| 18 | + CancellationToken cancellationToken, |
| 19 | + Action<HttpResponseMessage>? handlerResponse = null, |
| 20 | + Action<HttpResponseMessage>? handlerResponseByIsNotSuccessStatusCode = null) where T : notnull |
| 21 | + { |
| 22 | + HttpRequestMessage? request = null; |
| 23 | + bool requestIsSend = false; |
| 24 | + HttpResponseMessage? response = null; |
| 25 | + bool notDisposeResponse = false; |
| 26 | + try |
| 27 | + { |
| 28 | + request = requestFactory(); |
| 29 | + requestUri ??= request.RequestUri?.ToString(); |
| 30 | + |
| 31 | + if (!isCheckHttpUrl && !String2.IsHttpUrl(requestUri)) return default; |
| 32 | + |
| 33 | + //if (enableForward && IsAllowUrl(requestUri)) |
| 34 | + //{ |
| 35 | + // try |
| 36 | + // { |
| 37 | + // requestIsSend = true; |
| 38 | + // response = await Csc.Forward(request, |
| 39 | + // HttpCompletionOption.ResponseHeadersRead, |
| 40 | + // cancellationToken); |
| 41 | + // } |
| 42 | + // catch (Exception e) |
| 43 | + // { |
| 44 | + // logger.LogWarning(e, "CloudService Forward Fail, requestUri: {0}", requestUri); |
| 45 | + // response = null; |
| 46 | + // } |
| 47 | + //} |
| 48 | + |
| 49 | + if (response == null) |
| 50 | + { |
| 51 | + if (requestIsSend) |
| 52 | + { |
| 53 | + request.Dispose(); |
| 54 | + request = requestFactory(); |
| 55 | + } |
| 56 | + response = await client.SendAsync(request, |
| 57 | + HttpCompletionOption.ResponseHeadersRead, |
| 58 | + cancellationToken).ConfigureAwait(false); |
| 59 | + } |
| 60 | + |
| 61 | + handlerResponse?.Invoke(response); |
| 62 | + |
| 63 | + if (response.IsSuccessStatusCode) |
| 64 | + { |
| 65 | + if (response.Content != null) |
| 66 | + { |
| 67 | + var rspContentClrType = typeof(T); |
| 68 | + if (rspContentClrType == typeof(string)) |
| 69 | + { |
| 70 | + return (T)(object)await response.Content.ReadAsStringAsync(); |
| 71 | + } |
| 72 | + else if (rspContentClrType == typeof(byte[])) |
| 73 | + { |
| 74 | + return (T)(object)await response.Content.ReadAsByteArrayAsync(); |
| 75 | + } |
| 76 | + else if (rspContentClrType == typeof(Stream)) |
| 77 | + { |
| 78 | + notDisposeResponse = true; |
| 79 | + return (T)(object)await response.Content.ReadAsStreamAsync(); |
| 80 | + } |
| 81 | + var mime = response.Content.Headers.ContentType?.MediaType ?? accept; |
| 82 | + switch (mime) |
| 83 | + { |
| 84 | + case MediaTypeNames.JSON: |
| 85 | + case MediaTypeNames.XML: |
| 86 | + case MediaTypeNames.XML_APP: |
| 87 | + { |
| 88 | + using var stream = await response.Content |
| 89 | + .ReadAsStreamAsync().ConfigureAwait(false); |
| 90 | + using var reader = new StreamReader(stream, Encoding.UTF8); |
| 91 | + switch (mime) |
| 92 | + { |
| 93 | + case MediaTypeNames.JSON: |
| 94 | + { |
| 95 | + if (jsonSerializer == null) |
| 96 | + throw new NotSupportedException(null, new ArgumentNullException(nameof(jsonSerializer))); |
| 97 | + using var json = new JsonTextReader(reader); |
| 98 | + return jsonSerializer.Deserialize<T>(json); |
| 99 | + } |
| 100 | + case MediaTypeNames.XML: |
| 101 | + case MediaTypeNames.XML_APP: |
| 102 | + { |
| 103 | + var xmlSerializer = new XmlSerializer(typeof(T)); |
| 104 | + return (T?)xmlSerializer.Deserialize(reader); |
| 105 | + } |
| 106 | + } |
| 107 | + } |
| 108 | + break; |
| 109 | + } |
| 110 | + } |
| 111 | + } |
| 112 | + else |
| 113 | + { |
| 114 | + handlerResponseByIsNotSuccessStatusCode?.Invoke(response); |
| 115 | + } |
| 116 | + } |
| 117 | + catch (Exception e) |
| 118 | + { |
| 119 | + var knownType = e.GetKnownType(); |
| 120 | + if (knownType == ExceptionKnownType.Unknown) |
| 121 | + { |
| 122 | + logger.LogError(e, "SendAsync fail, requestUri: {0}", requestUri); |
| 123 | + } |
| 124 | + } |
| 125 | + finally |
| 126 | + { |
| 127 | + request?.Dispose(); |
| 128 | + if (!notDisposeResponse) |
| 129 | + { |
| 130 | + response?.Dispose(); |
| 131 | + } |
| 132 | + } |
| 133 | + return default; |
| 134 | + } |
| 135 | + |
| 136 | + [MethodImpl(MethodImplOptions.AggressiveInlining)] |
| 137 | + public static Task<T?> SendAsync<T>( |
| 138 | + this HttpClient client, |
| 139 | + ILogger logger, |
| 140 | + JsonSerializer? jsonSerializer, |
| 141 | + string? requestUri, |
| 142 | + Func<HttpRequestMessage> requestFactory, |
| 143 | + string? accept, |
| 144 | + //bool enableForward, |
| 145 | + CancellationToken cancellationToken, |
| 146 | + Action<HttpResponseMessage>? handlerResponse = null, |
| 147 | + Action<HttpResponseMessage>? handlerResponseByIsNotSuccessStatusCode = null) where T : notnull |
| 148 | + { |
| 149 | + return client.SendAsync<T>( |
| 150 | + logger, |
| 151 | + jsonSerializer, |
| 152 | + isCheckHttpUrl: false, |
| 153 | + requestUri, |
| 154 | + requestFactory, |
| 155 | + accept, |
| 156 | + //enableForward, |
| 157 | + cancellationToken, |
| 158 | + handlerResponse, |
| 159 | + handlerResponseByIsNotSuccessStatusCode); |
| 160 | + } |
| 161 | + |
| 162 | + [MethodImpl(MethodImplOptions.AggressiveInlining)] |
| 163 | + public static Task<T?> GetAsync<T>( |
| 164 | + this HttpClient client, |
| 165 | + ILogger logger, |
| 166 | + string requestUri, |
| 167 | + string accept = MediaTypeNames.JSON, |
| 168 | + CancellationToken cancellationToken = default, |
| 169 | + string? cookie = null, |
| 170 | + string? userAgent = null, |
| 171 | + JsonSerializer? jsonSerializer = null) where T : notnull |
| 172 | + { |
| 173 | + if (!String2.IsHttpUrl(requestUri)) |
| 174 | + return Task.FromResult(default(T?)); |
| 175 | + return client.SendAsync<T>(logger, jsonSerializer, isCheckHttpUrl: true, requestUri, () => |
| 176 | + { |
| 177 | + var request = new HttpRequestMessage(HttpMethod.Get, requestUri); |
| 178 | + if (cookie != null) |
| 179 | + { |
| 180 | + request.Headers.Add("Cookie", cookie); |
| 181 | + } |
| 182 | + request.Headers.Accept.ParseAdd(accept); |
| 183 | + if (userAgent != null) |
| 184 | + request.Headers.UserAgent.ParseAdd(userAgent); |
| 185 | + return request; |
| 186 | + }, accept/*, true*/, cancellationToken); |
| 187 | + } |
| 188 | +} |
0 commit comments