-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy pathDefaultHttpClient.cs
41 lines (37 loc) · 1.23 KB
/
DefaultHttpClient.cs
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
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Threading.Tasks;
namespace WSNet2
{
/// <summary>
/// System.Net.Http.HttpClientを使ったPOSTの実装
/// </summary>
static class DefaultHttpClient
{
static HttpClient client;
public static void Post(string url, IReadOnlyDictionary<string, string> headers, byte[] content, TaskCompletionSource<(int, byte[])> tcs)
{
Task.Run(async () =>
{
try
{
var request = new HttpRequestMessage(HttpMethod.Post, url);
request.Content = new ByteArrayContent(content);
foreach (var kv in headers)
{
request.Headers.Add(kv.Key, kv.Value);
}
client ??= new HttpClient();
var res = await client.SendAsync(request);
var body = await res.Content.ReadAsByteArrayAsync();
tcs.TrySetResult(((int)res.StatusCode, body));
}
catch (Exception e)
{
tcs.TrySetException(e);
}
});
}
}
}