发送http、https请求
/// <summary> /// 发送http、https请求 /// .net framework4.6.2 /// </summary> /// <param name="url"></param> /// <param name="method"></param> /// <param name="postContent"></param> /// <returns></returns> public static async Task SendRequestAsync(string url, string method, string postContent) { //信任所有证书,使用Tls1.2协议,支持https。 ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult); ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; try { using (var client = new HttpClient()) { if (method == "post") { StringContent content = new StringContent(postContent, Encoding.UTF8); var httpRequestMessage = new HttpRequestMessage(HttpMethod.Post, url); httpRequestMessage.Content = content; // 发送 POST 请求 var httpResponseMessage = await client.SendAsync(httpRequestMessage); if (httpResponseMessage.IsSuccessStatusCode) { using (var contentStream = await httpResponseMessage.Content.ReadAsStreamAsync()) { using (StreamReader sw = new StreamReader(contentStream)) { string res = sw.ReadToEnd(); Console.WriteLine($"POST请求成功,返回结果: {res}"); } } } else { Console.WriteLine($"POST请求失败: {JsonConvert.SerializeObject(httpResponseMessage)}"); } } else { // 发送 GET 请求 var response = await client.GetAsync(url); if (response.IsSuccessStatusCode) { string content = await response.Content.ReadAsStringAsync(); Console.WriteLine($"GET请求成功,返回结果: {content}"); } else { Console.WriteLine($"GET请求失败: {JsonConvert.SerializeObject(response)}"); } } } } catch (HttpRequestException ex) { Console.WriteLine($"发送请求异常: {ex.Message}"); } }
C#发送https请求有一点要注意:
ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
httpRequest.ProtocolVersion = HttpVersion.Version10;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3;
否则会报错:未能建立安全的SSL/TLS通道
发送请求代码:
/// <summary> /// 发送请求(get/post/http/https) /// </summary> /// <param name="Uri">请求地址</param> /// <param name="JsonStr">json数据</param> /// <param name="Method">请求方式POST/GET</param> /// <returns></returns> public static string ClientRequest(string Uri, string JsonStr, string Method = "POST") { try { var httpRequest = (HttpWebRequest)HttpWebRequest.Create(Uri); httpRequest.Method = Method; httpRequest.ContentType = "application/json"; if (Method.ToLower() == "get") { httpRequest.ContentType = "application/x-www-form-urlencoded"; } httpRequest.Proxy = null; httpRequest.UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 6.1; zh-CN; rv:1.9.2.13) Gecko/20101203 Firefox/3.6.13"; httpRequest.Headers.Add("Accept-Language", "zh-cn,en-us;q=0.8,zh-hk;q=0.6,ja;q=0.4,zh;q=0.2"); httpRequest.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"; //如果是发送HTTPS请求 if (Uri.StartsWith("https", StringComparison.OrdinalIgnoreCase)) { ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult); httpRequest.ProtocolVersion = HttpVersion.Version10; ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3; } else { ServicePointManager.ServerCertificateValidationCallback = delegate { return true; }; ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; } if (!string.IsNullOrEmpty(JsonStr)) { using (var dataStream = new StreamWriter(httpRequest.GetRequestStream())) { dataStream.Write(JsonStr); dataStream.Flush(); dataStream.Close(); } } var httpResponse = (HttpWebResponse)httpRequest.GetResponse(); using (var dataStream = new StreamReader(httpResponse.GetResponseStream())) { var result = dataStream.ReadToEnd(); return result; } } catch (Exception ex) { return "{\"error\":\"" + ex.Message + "\"}"; } } private static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors) { return true; //总是接受 }
//接收示例
Response.ContentType = "application/json";
Response.Cache.SetCacheability(HttpCacheability.NoCache);
using (var reader = new System.IO.StreamReader(Request.InputStream))
{
string xmlData = reader.ReadToEnd();
if (!string.IsNullOrEmpty(xmlData))
{
//业务处理
JavaScriptSerializer jss = new JavaScriptSerializer();
PushModel model = jss.Deserialize(xmlData, typeof(PushModel)) as PushModel;
if (model != null)
{
channel_ids = model.channel_id;
msg = model.msg;
}
}
}
.netframework4.7.2
public async Task TestSendHttp()
{
HttpClient httpClient = new HttpClient();
string url = "https://blog.csdn.net/huzia/article/details/109073895";
var httpRequestMessage = new HttpRequestMessage(HttpMethod.Post, url);
var httpResponseMessage = await httpClient.SendAsync(httpRequestMessage);
if (httpResponseMessage.IsSuccessStatusCode)
{
using (var contentStream = await httpResponseMessage.Content.ReadAsStreamAsync())
{
using (StreamReader sw = new StreamReader(contentStream))
{
string res = sw.ReadToEnd();
Response.Write(res);
}
}
}
}
.netcore3.1 private readonly IHttpClientFactory _httpClientFactory; 构造函数注入
public async Task TestSendHttp() {
string url = "https://blog.csdn.net/huzia/article/details/109073895";
//var httpRequestMessage = new HttpRequestMessage(HttpMethod.Get, url)
//{
// Headers =
// {
// { HeaderNames.Accept, "application/x-www-form-urlencoded" },
// { HeaderNames.UserAgent, "Mozilla/5.0 (Windows; U; Windows NT 6.1; zh-CN; rv:1.9.2.13) Gecko/20101203 Firefox/3.6.13" }
// }
//};
var httpRequestMessage = new HttpRequestMessage(HttpMethod.Post, url);
var httpClient = _httpClientFactory.CreateClient();
var httpResponseMessage = await httpClient.SendAsync(httpRequestMessage);
if (httpResponseMessage.IsSuccessStatusCode)
{
using var contentStream = await httpResponseMessage.Content.ReadAsStreamAsync();
using StreamReader sw = new StreamReader(contentStream);
string res = sw.ReadToEnd();
await Response.WriteAsync(res);
}
}
/// <summary>
/// 发送请求
/// </summary>
/// <param name="url"></param>
/// <param name="method"></param>
/// <param name="token"></param>
/// <param name="data"></param>
/// <returns></returns>
public static async Task<string> SendRequest(string url, HttpMethod method, string token, string data)
{
using var request = new HttpRequestMessage(method, url);
request.Content = new StringContent(data, Encoding.UTF8, "application/json");
if (!string.IsNullOrEmpty(token))
{
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
}
var httpResponseMessage = await httpClient.SendAsync(request).ConfigureAwait(false);
if (httpResponseMessage.IsSuccessStatusCode)
{
string res = await httpResponseMessage.Content.ReadAsStringAsync();
return res;
}
else
{
var obj = new ApiResult<object>()
{
Data = null,
ErrorCode = httpResponseMessage.StatusCode.ToString(),
Message = "发送请求失败"
};
return JsonSerializer.Serialize(obj);
}
}
http://blog.csdn.net/lsm135/article/details/50367315
浙公网安备 33010602011771号