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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | 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; 构造函数注入
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | 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); } } |
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 | /// <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
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· DeepSeek 解答了困扰我五年的技术问题
· 为什么说在企业级应用开发中,后端往往是效率杀手?
· 用 C# 插值字符串处理器写一个 sscanf
· Java 中堆内存和栈内存上的数据分布和特点
· 开发中对象命名的一点思考
· 为什么说在企业级应用开发中,后端往往是效率杀手?
· DeepSeek 解答了困扰我五年的技术问题。时代确实变了!
· 本地部署DeepSeek后,没有好看的交互界面怎么行!
· 趁着过年的时候手搓了一个低代码框架
· 推荐一个DeepSeek 大模型的免费 API 项目!兼容OpenAI接口!