C#使用HttpClient

C#使用HttpClient

這篇介紹在C#上使用HttpClient

Restful API: GET

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
private static readonly string DefaultMediaType = "application/json";

public static byte[] GET(string url, NameValueCollection values, int timeOut)
{
try
{
if (values != null)
{
url = url + "?" + ToQueryString(values);
}

byte[] result = null;
using (var client = new HttpClient())
{
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(DefaultMediaType));
client.Timeout = TimeSpan.FromMilliseconds(timeOut);
result = client.GetByteArrayAsync(url).Result;
string str = Encoding.Default.GetString(result);
Console.WriteLine(str);
}
return result;
}
catch (Exception ex)
{
LogUtil.logger.Error("Get failed:" + url);
LogUtil.logger.Error(Convert.ToString(ex));
return null;
}
}
private static string ToQueryString(NameValueCollection col)
{
return string.Join("&", col.AllKeys.Select(key => string.Format("{0}={1}", HttpUtility.UrlEncode(key), HttpUtility.UrlEncode(col[key]))));
}
private static IDictionary<string, string> ToDictionary(this NameValueCollection source)
{
return source.AllKeys.ToDictionary(k => k, k => source[k]);
}

Restful API: POST

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
private static readonly string DefaultMediaType = "application/json";

public static string POST(string url, NameValueCollection values, int timeOut)
{
string result = "";
try
{
using (var client = new HttpClient())
{
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(DefaultMediaType));
client.Timeout = TimeSpan.FromMilliseconds(timeOut);
HttpContent contentPost = null;
if (values != null)
{
var json = JsonConvert.SerializeObject(values.ToDictionary());
contentPost = new StringContent(json, Encoding.UTF8, DefaultMediaType);
}

ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls;

HttpResponseMessage response = client.PostAsync(url, contentPost).GetAwaiter().GetResult();
result = response.Content.ReadAsStringAsync().GetAwaiter().GetResult();
}
}
catch(Exception ex)
{
LogUtil.logger.Error("Post failed:" + url);
LogUtil.logger.Error(Convert.ToString(ex));
}
return result;
}

private static IDictionary<string, string> ToDictionary(this NameValueCollection source)
{
return source.AllKeys.ToDictionary(k => k, k => source[k]);
}