-
Notifications
You must be signed in to change notification settings - Fork 23
Expand file tree
/
Copy pathNativeHttpClientHelper.cs
More file actions
76 lines (63 loc) · 2.97 KB
/
Copy pathNativeHttpClientHelper.cs
File metadata and controls
76 lines (63 loc) · 2.97 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
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
namespace SMSApi.Api
{
public static class NativeHttpClientHelper
{
public static async Task<HttpResponseEntity> SendRequest(
this HttpClient httpClient,
RequestMethod method,
string uri,
NameValueCollection body = null,
Dictionary<string, Stream> files = null,
CancellationToken cancellationToken = default
)
{
HttpContent httpContent;
switch (method)
{
case RequestMethod.GET:
var getResponse = await httpClient.GetAsync(uri, cancellationToken);
return new HttpResponseEntity(getResponse.Content.ReadAsStreamAsync(), getResponse.StatusCode);
case RequestMethod.POST:
httpContent = ConvertNameValueCollectionToHttpContent(body, files);
var postResponse = await httpClient.PostAsync(uri, httpContent, cancellationToken);
return new HttpResponseEntity(postResponse.Content.ReadAsStreamAsync(), postResponse.StatusCode);
case RequestMethod.PUT:
httpContent = ConvertNameValueCollectionToHttpContent(body, files);
var putResponse = await httpClient.PutAsync(uri, httpContent, cancellationToken);
return new HttpResponseEntity(putResponse.Content.ReadAsStreamAsync(), putResponse.StatusCode);
case RequestMethod.DELETE:
var deleteResult = await httpClient.DeleteAsync(uri, cancellationToken);
return new HttpResponseEntity(deleteResult.Content.ReadAsStreamAsync(), deleteResult.StatusCode);
default:
throw new ArgumentOutOfRangeException(nameof(method), method, null);
}
}
private static HttpContent ConvertNameValueCollectionToHttpContent(
NameValueCollection collection,
Dictionary<string, Stream> files = null
)
{
var contentCollectionKeys = collection.AllKeys;
var contentCollection = contentCollectionKeys
.Select(key => new KeyValuePair<string, string>(key, collection[key]))
.ToList();
var formUrlEncodedContent = new FormUrlEncodedContent(contentCollection);
if (files == null) return formUrlEncodedContent;
var multipartContent = new MultipartFormDataContent();
foreach (var keyValuePair in contentCollection)
multipartContent.Add(new StringContent(keyValuePair.Value), keyValuePair.Key);
files
.ToList()
.ForEach(pair => multipartContent.Add(new StreamContent(pair.Value), "file", pair.Key));
return multipartContent;
}
}
}