Extract response exceptions
[smsapi-csharp.git] / smsapi / NativeHttpClientHelper.cs
blob3ba035025d8ce31c58398ad2539f135beaf8f47c
1 using System;
2 using System.Collections.Generic;
3 using System.Collections.Specialized;
4 using System.IO;
5 using System.Linq;
6 using System.Net.Http;
7 using System.Threading;
8 using System.Threading.Tasks;
10 namespace SMSApi.Api
12 public static class NativeHttpClientHelper
14 public static async Task<HttpResponseEntity> SendRequest(
15 this HttpClient httpClient,
16 RequestMethod method,
17 string uri,
18 NameValueCollection body = null,
19 Dictionary<string, Stream> files = null,
20 CancellationToken cancellationToken = default
23 HttpContent httpContent;
25 switch (method)
27 case RequestMethod.GET:
28 var getResponse = await httpClient.GetAsync(uri, cancellationToken);
30 return new HttpResponseEntity(getResponse.Content.ReadAsStreamAsync(), getResponse.StatusCode);
31 case RequestMethod.POST:
32 httpContent = ConvertNameValueCollectionToHttpContent(body, files);
33 var postResponse = await httpClient.PostAsync(uri, httpContent, cancellationToken);
35 return new HttpResponseEntity(postResponse.Content.ReadAsStreamAsync(), postResponse.StatusCode);
36 case RequestMethod.PUT:
37 httpContent = ConvertNameValueCollectionToHttpContent(body, files);
38 var putResponse = await httpClient.PutAsync(uri, httpContent, cancellationToken);
40 return new HttpResponseEntity(putResponse.Content.ReadAsStreamAsync(), putResponse.StatusCode);
41 case RequestMethod.DELETE:
42 var deleteResult = await httpClient.DeleteAsync(uri, cancellationToken);
44 return new HttpResponseEntity(deleteResult.Content.ReadAsStreamAsync(), deleteResult.StatusCode);
45 default:
46 throw new ArgumentOutOfRangeException(nameof(method), method, null);
50 private static HttpContent ConvertNameValueCollectionToHttpContent(
51 NameValueCollection collection,
52 Dictionary<string, Stream> files = null
55 var contentCollectionKeys = collection.AllKeys;
57 var contentCollection = contentCollectionKeys
58 .Select(key => new KeyValuePair<string, string>(key, collection[key]))
59 .ToList();
60 var formUrlEncodedContent = new FormUrlEncodedContent(contentCollection);
62 if (files == null) return formUrlEncodedContent;
64 var multipartContent = new MultipartFormDataContent();
66 foreach (var keyValuePair in contentCollection)
67 multipartContent.Add(new StringContent(keyValuePair.Value), keyValuePair.Key);
69 files
70 .ToList()
71 .ForEach(pair => multipartContent.Add(new StreamContent(pair.Value), "file", pair.Key));
73 return multipartContent;