赞
踩
一、HttpClient发送请求
1、发送Get请求
// 请求地址:url
using(var client = new HttpClient())
{
var response = await client.GetStringAsync(url);
return response;
}
2、发送Post请求
// 格式:application/json using(var client = new HttpClient()) { var response = await client.PostAsync(url, new StringContent(json, Encoding.UTF8, "application/json")); var content = response.Content.ReadAsStringAsync(); return content; } // 格式:x-www-form-urlencoded using(var client = new HttpClient()) { var form = new Dictionary<string, string>(); form.Add("name", "jerry") form.Add("password", "123"); var response = await client.PostAsync(url, new FormUrlEncodedContent(form)); var content = response.Content.ReadAsStringAsync(); return content; } // 格式:multipart/form-data
二、WebClient发送请求
1、发送Get请求
/// <summary>
/// Get请求
/// </summary>
/// <param name="url">请求地址</param>
public string Get(string url)
{
using(var client = new WebClient())
{
var response = client.DownloadString(url);
return response;
}
}
三、HttpWebRequest发送请求
1、发送Get请求
/// <summary> /// Get请求 /// </summary> /// <param name="url">请求地址</param> public string Get(string url) { var request = (HttpWebRequest)WebRequest.Create(url); using(var response = (HttpWebResponse)request.GetResponse()) { if(response.StatusCode == HttpStatusCode.OK) { using(var reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8)) { var content = reader.ReadToEnd(); return content; } } } }
注意:在asp.net项目中,使用https发送请求前必须设置:SecurityProtocol,否则会报错:
- 请求被中止: 未能创建 SSL/TLS 安全通道,
- 或基础连接已经关闭: 发送时发生错误。
// asp.net发送请求前必须设置:SecurityProtocol
ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。