-
Notifications
You must be signed in to change notification settings - Fork 318
Expand file tree
/
Copy pathSystemNetHttpClient.cs
More file actions
169 lines (147 loc) · 6.08 KB
/
Copy pathSystemNetHttpClient.cs
File metadata and controls
169 lines (147 loc) · 6.08 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
#if !NET35
using System;
using System.IO;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using System.Runtime.InteropServices;
namespace Twilio.Http
{
/// <summary>
/// Sample client to make HTTP requests
/// </summary>
public class SystemNetHttpClient : HttpClient
{
#if NET451
private string PlatVersion = ".NET Framework 4.5.1+";
#else
private string PlatVersion = RuntimeInformation.FrameworkDescription;
#endif
private readonly System.Net.Http.HttpClient _httpClient;
/// <summary>
/// Create new HttpClient
/// </summary>
/// <param name="httpClient">HTTP client to use</param>
public SystemNetHttpClient(System.Net.Http.HttpClient httpClient = null)
{
_httpClient = httpClient ?? new System.Net.Http.HttpClient(new HttpClientHandler() { AllowAutoRedirect = false });
}
/// <summary>
/// Make a synchronous request
/// </summary>
/// <param name="request">Twilio request</param>
/// <returns>Twilio response</returns>
public override Response MakeRequest(Request request)
{
try
{
var task = MakeRequestAsync(request);
task.Wait();
return task.Result;
}
catch (AggregateException ae)
{
// Combine nested AggregateExceptions
ae = ae.Flatten();
throw ae.InnerExceptions[0];
}
}
/// <summary>
/// Make an asynchronous request
/// </summary>
/// <param name="request">Twilio response</param>
/// <returns>Task that resolves to the response</returns>
public override async Task<Response> MakeRequestAsync(Request request)
{
var httpRequest = BuildHttpRequest(request);
if (!Equals(request.Method, HttpMethod.Get))
{
if (request.Files.Count > 0)
{
var boundary = "---------" + Guid.NewGuid().ToString().ToLower();
var multiPartContent = new MultipartFormDataContent(boundary);
multiPartContent.Headers.ContentType = new MediaTypeHeaderValue("multipart/form-data")
{
Parameters = { new NameValueHeaderValue("boundary", boundary) }
};
foreach (var postParam in request.PostParams)
{
multiPartContent.Add(new StringContent(postParam.Value), postParam.Key);
}
foreach (var file in request.Files)
{
multiPartContent.Add(new StreamContent(file.Value.Stream), file.Key, file.Value.FileName);
}
httpRequest.Content = multiPartContent;
}
else
{
httpRequest.Content = new FormUrlEncodedContent(request.PostParams);
}
}
this.LastRequest = request;
this.LastResponse = null;
var httpResponse = await _httpClient.SendAsync(httpRequest).ConfigureAwait(false);
var reader = new StreamReader(await httpResponse.Content.ReadAsStreamAsync().ConfigureAwait(false));
// Create and return a new Response. Keep a reference to the last
// response for debugging, but don't return it as it may be shared
// among threads.
var response = new Response(httpResponse.StatusCode, await reader.ReadToEndAsync().ConfigureAwait(false), httpResponse.Headers);
this.LastResponse = response;
return response;
}
private HttpRequestMessage BuildHttpRequest(Request request)
{
var httpRequest = new HttpRequestMessage(
new System.Net.Http.HttpMethod(request.Method.ToString()),
request.ConstructUrl()
);
var authBytes = Authentication(request.Username, request.Password);
httpRequest.Headers.Authorization = new AuthenticationHeaderValue("Basic", authBytes);
httpRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
httpRequest.Headers.AcceptEncoding.Add(new StringWithQualityHeaderValue("utf-8"));
int lastSpaceIndex = PlatVersion.LastIndexOf(" ");
System.Text.StringBuilder PlatVersionSb= new System.Text.StringBuilder(PlatVersion);
PlatVersionSb[lastSpaceIndex] = '/';
string helperLibVersion = AssemblyInfomation.AssemblyInformationalVersion;
string osName = "Unknown";
#if !NETSTANDARD1_4
osName = Environment.OSVersion.Platform.ToString();
#else
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
osName = "Windows";
}
else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
{
osName = "MacOS";
}
else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
{
osName = "Linux";
}
#endif
string osArch;
#if !NET451
osArch = RuntimeInformation.OSArchitecture.ToString();
#else
osArch = Environment.GetEnvironmentVariable("PROCESSOR_ARCHITECTURE") ?? "Unknown";
#endif
var libraryVersion = String.Format("twilio-csharp/{0} ({1} {2}) {3}", helperLibVersion, osName, osArch, PlatVersionSb);
if (request.UserAgentExtensions != null)
{
foreach (var extension in request.UserAgentExtensions)
{
libraryVersion += " " + extension;
}
}
httpRequest.Headers.TryAddWithoutValidation("User-Agent", libraryVersion);
foreach (var header in request.HeaderParams)
{
httpRequest.Headers.TryAddWithoutValidation(header.Key, header.Value);
}
return httpRequest;
}
}
}
#endif