static U MakeRequest<T, U, EX>( string method, AuthenticationDetails auth, string path, NameValueCollection queryArguments, T payload, string baseUri, string contentType) where T : class where EX : ErrorResult { JsonSerializerSettings serialiserSettings = new JsonSerializerSettings(); serialiserSettings.NullValueHandling = NullValueHandling.Ignore; serialiserSettings.MissingMemberHandling = MissingMemberHandling.Ignore; #if SUPPORTED_FRAMEWORK_VERSION serialiserSettings.Converters.Add(new EmailAddressConverter()); #endif string uri = baseUri + path + NameValueCollectionExtension.ToQueryString(queryArguments); HttpWebRequest req = (HttpWebRequest)WebRequest.Create(uri); req.Method = method; req.ContentType = contentType; req.AutomaticDecompression = DecompressionMethods.GZip; if (auth != null) { if (auth is OAuthAuthenticationDetails) { OAuthAuthenticationDetails oauthDetails = auth as OAuthAuthenticationDetails; req.Headers["Authorization"] = "Bearer " + oauthDetails.AccessToken; } else if (auth is ApiKeyAuthenticationDetails) { ApiKeyAuthenticationDetails apiKeyDetails = auth as ApiKeyAuthenticationDetails; req.Headers["Authorization"] = "Basic " + Convert.ToBase64String( Encoding.Default.GetBytes(apiKeyDetails.ApiKey + ":x")); } else if (auth is BasicAuthAuthenticationDetails) { BasicAuthAuthenticationDetails basicDetails = auth as BasicAuthAuthenticationDetails; req.Headers["Authorization"] = "Basic " + Convert.ToBase64String( Encoding.Default.GetBytes(basicDetails.Username + ":" + basicDetails.Password)); } } req.UserAgent = string.Format("createsend-dotnet-#{0} .Net: {1} OS: {2} DLL: {3}", CreateSendOptions.VersionNumber, Environment.Version, Environment.OSVersion, Assembly.GetExecutingAssembly().FullName); if (method != "GET") { if (payload != null) { using (System.IO.StreamWriter os = new System.IO.StreamWriter(req.GetRequestStream())) { if (contentType == APPLICATION_FORM_URLENCODED_CONTENT_TYPE) os.Write(payload); else os.Write(JsonConvert.SerializeObject(payload, Formatting.None, serialiserSettings)); os.Close(); } } else req.ContentLength = 0; } try { using (var resp = (HttpWebResponse)req.GetResponse()) { if (resp == null) return default(U); else { using (var sr = new System.IO.StreamReader(resp.GetResponseStream())) { #if SUPPORTED_FRAMEWORK_VERSION var type = typeof(U); if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(RateLimited<>)) { var responseType = type.GetGenericArguments()[0]; var response = JsonConvert.DeserializeObject(sr.ReadToEnd().Trim(), responseType, serialiserSettings); var status = new RateLimitStatus { Credit = resp.Headers["X-RateLimit-Limit"].UInt(0), Remaining = resp.Headers["X-RateLimit-Remaining"].UInt(0), Reset = resp.Headers["X-RateLimit-Reset"].UInt(0) }; return (U)Activator.CreateInstance(type, response, status); } #endif return JsonConvert.DeserializeObject<U>(sr.ReadToEnd().Trim(), serialiserSettings); } } } } catch (WebException we) { if (we.Status == WebExceptionStatus.ProtocolError) { switch ((int)((HttpWebResponse)we.Response).StatusCode) { case 400: case 401: throw ThrowReworkedCustomException<EX>(we); case 404: default: throw we; } } else { throw we; } } }
private static async Task <U> MakeRequestAsync <T, U, EX>( string method, AuthenticationDetails auth, string path, NameValueCollection queryArguments, T payload, string baseUri, string contentType) where T : class where EX : ErrorResult { try { JsonSerializerSettings serialiserSettings = new JsonSerializerSettings(); serialiserSettings.NullValueHandling = NullValueHandling.Ignore; serialiserSettings.MissingMemberHandling = MissingMemberHandling.Ignore; serialiserSettings.Converters.Add(new EmailAddressConverter()); string uri = baseUri + path + NameValueCollectionExtension.ToQueryString(queryArguments); HttpClientHandler handler = new HttpClientHandler(); handler.AutomaticDecompression = System.Net.DecompressionMethods.GZip; HttpClient client = new HttpClient(handler); if (auth != null) { if (auth is OAuthAuthenticationDetails) { OAuthAuthenticationDetails oauthDetails = auth as OAuthAuthenticationDetails; client.DefaultRequestHeaders.Add("Authorization", "Bearer " + oauthDetails.AccessToken); } else if (auth is ApiKeyAuthenticationDetails) { ApiKeyAuthenticationDetails apiKeyDetails = auth as ApiKeyAuthenticationDetails; client.DefaultRequestHeaders.Add("Authorization", "Basic " + Convert.ToBase64String( Encoding.GetEncoding(0).GetBytes(apiKeyDetails.ApiKey + ":x"))); } else if (auth is BasicAuthAuthenticationDetails) { BasicAuthAuthenticationDetails basicDetails = auth as BasicAuthAuthenticationDetails; client.DefaultRequestHeaders.Add("Authorization", "Basic " + Convert.ToBase64String( Encoding.GetEncoding(0).GetBytes(basicDetails.Username + ":" + basicDetails.Password))); } } HttpContent content = null; HttpResponseMessage response = null; if (method != "GET") { Stream s = new MemoryStream(); Stream requestStream = new MemoryStream(); if (payload != null) { using (System.IO.StreamWriter os = new System.IO.StreamWriter(s)) { if (contentType == APPLICATION_FORM_URLENCODED_CONTENT_TYPE) { os.Write(payload); } else { string json = JsonConvert.SerializeObject(payload, Formatting.None, serialiserSettings); os.Write(json); } await os.FlushAsync(); s.Seek(0, SeekOrigin.Begin); await s.CopyToAsync(requestStream); os.Dispose(); } requestStream.Seek(0, SeekOrigin.Begin); content = new StreamContent(requestStream); response = await client.PostAsync(uri, content); } else { response = await client.PostAsync(uri, null); } } else { response = await client.GetAsync(uri); } if (response.IsSuccessStatusCode) { var resp = await response.Content.ReadAsStreamAsync(); if (resp == null) { return(default(U)); } { using (var sr = new System.IO.StreamReader(resp)) { var type = typeof(U); if (type.GetGenericTypeDefinition() == typeof(RateLimited <>)) { var responseType = type.GenericTypeArguments[0]; var result = JsonConvert.DeserializeObject(sr.ReadToEnd().Trim(), responseType, serialiserSettings); var status = new RateLimitStatus { Credit = response.Headers.Contains("X-RateLimit-Limit") ? uint.Parse(response.Headers.GetValues("X-RateLimit-Limit").First()) : 0, Remaining = response.Headers.Contains("X-RateLimit-Remaining") ? uint.Parse(response.Headers.GetValues("X-RateLimit-Remaining").First()) : 0, Reset = response.Headers.Contains("X-RateLimit-Reset") ? uint.Parse(response.Headers.GetValues("X-RateLimit-Reset").First()) : 0 }; return((U)Activator.CreateInstance(type, result, status)); } return(JsonConvert.DeserializeObject <U>(sr.ReadToEnd().Trim(), serialiserSettings)); } } } else { switch (response.StatusCode) { case System.Net.HttpStatusCode.BadRequest: case System.Net.HttpStatusCode.Unauthorized: throw ThrowReworkedCustomException <EX>(response); case System.Net.HttpStatusCode.NotFound: default: throw new HttpRequestException(response.Content.ReadAsStringAsync().Result); } } } catch (Exception ex) { throw; } }