2 using System
.Collections
.Generic
;
3 using System
.Collections
.Specialized
;
7 using System
.Threading
;
8 using System
.Threading
.Tasks
;
12 public static class NativeHttpClientHelper
14 public static async Task
<HttpResponseEntity
> SendRequest(
15 this HttpClient httpClient
,
18 NameValueCollection body
= null,
19 Dictionary
<string, Stream
> files
= null,
20 CancellationToken cancellationToken
= default
23 HttpContent httpContent
;
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
);
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
]))
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
);
71 .ForEach(pair
=> multipartContent
.Add(new StreamContent(pair
.Value
), "file", pair
.Key
));
73 return multipartContent
;