/// <summary>
/// 使用post方法异步请求
/// </summary>
/// <param name="url">目标链接</param>
/// <param name="json">发送的参数字符串,只能用json</param>
/// <returns>返回的字符串</returns>
public async Task<string> PostAsyncJson(string url, string json, Dictionary<string, string> header = null, bool Gzip = false)
{
HttpClient client = new HttpClient(new HttpClientHandler() { UseCookies = false });
HttpContent content = new StringContent(json);
content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
if (header != null)
{
client.DefaultRequestHeaders.Clear();
foreach (var item in header)
{
client.DefaultRequestHeaders.Add(item.Key, item.Value);
}
}
HttpResponseMessage response = await client.PostAsync(url, content);
response.EnsureSuccessStatusCode();
string responseBody = "";
if (Gzip)
{
GZipInputStream inputStream = new GZipInputStream(await response.Content.ReadAsStreamAsync());
responseBody = new StreamReader(inputStream).ReadToEnd();
}
else
{
responseBody = await response.Content.ReadAsStringAsync();
}
return responseBody;
}
使用post方法异步请求
最新推荐文章于 2024-01-10 11:05:17 发布