HttpWebRequest WebClient给远程服务器上传数据; 未能创建 SSL/TLS 安全通道;JSON字符长度超出限制;
未能创建 SSL/TLS 安全通道,添加两句:
ServicePointManager.ServerCertificateValidationCallback += (s, cert, chain, sslPolicyErrors) => true;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;
WebClient给远程服务器上传数据
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 | public void UploadDataWeatherHourly(List<WeatherHourly> list) { try { using (WebClient client = new WebClient()) { ServicePointManager.ServerCertificateValidationCallback += (s, cert, chain, sslPolicyErrors) => true ; ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls; var address = "" ; address = System.Configuration.ConfigurationManager.AppSettings[ "UploadUrlHourly" ]; client.Headers[HttpRequestHeader.ContentType] = "application/json" ; client.Encoding = System.Text.Encoding.UTF8; //Encryption en = new Encryption(); //var list2 = new List<WeatherHourly>() { }; //for (int i = 0; i < 100; i++) //{ // list2.Add(list[i]); //} //var postData = en.ByteTo16(en.EncryptObjByte(list)); var data = new PostWeatherHourly { data = list }; string response1 = client.UploadString(address, JsonConvert.SerializeObject(data)); var result = JsonConvert.DeserializeObject<ResultModel>(response1); LogManage.Info( "小时上传数量:" + list.Count.ToString()); LogManage.Info( "小时入库成功数量:" +result.total.ToString()+ " 返回信息:" + result.msg); } } catch (Exception ex) { LogManage.Error( "UploadDataWeatherHourly" , ex); } } |
C# MVC 控制器接收数据
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 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 | [HttpPost] public JsonResult AddDataHourly(PostWeatherHourly obj) { ResultModel result = new Models.ResultModel(); var referer = Request.UrlReferrer; if (referer != null && referer.IsAbsoluteUri) { result.msg = "Referrer validate fail!" ; return Json(result); } Encryption en = new Encryption(); try { //var temp = en.Str16ToByte(obj.data); //var list = en.DecryptObj<List<WeatherHourly>>(temp); //var num = WeatherHourlyAddRange(list); var num = WeatherHourlyAddRange(obj.data); result.msg = "AddDataHourly成功" ; result.success = true ; result.total = num; } catch (Exception ex) { result.msg = ex.Message; result.success = false ; } return Json(result); } public int WeatherHourlyAddRange(List<WeatherHourly> weatherHourlyList) { int num = -1; using ( var db = new EcologyServiceEntities()) { var tran = db.Database.BeginTransaction(); //开启事务 try { db.WeatherHourly.AddRange(weatherHourlyList); if (weatherHourlyList.Count > 0) { num = db.SaveChanges(); tran.Commit(); //必须调用Commit(),不然数据不会保存 } } catch (Exception ex) { tran.Rollback(); //出错就回滚 //LogManage.Error("小时数据报错", ex); //若重复错误,则逐条遍历。 while (ex.InnerException != null ) { ex = ex.InnerException; if (ex.Message.Contains( "IX_" )) { foreach ( var myObj in weatherHourlyList) { try { using ( var db3 = new EcologyServiceEntities()) { db3.WeatherHourly.Add(myObj); db3.SaveChanges(); } } catch (Exception ex2) { } } } } } } return num; } |
数据接收类
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | public class PostWeatherHourly { public List<WeatherHourly> data { get ; set ; } } public class WeatherHourly { public int ID { get ; set ; } public Nullable< int > StationID { get ; set ; } public System.DateTime RecordDate { get ; set ; } public int DataHour { get ; set ; } public Nullable< double > Temperature { get ; set ; } public Nullable< double > AirPressure { get ; set ; } public Nullable< double > Rainfall { get ; set ; } public Nullable< double > RelativeHumidity { get ; set ; } public Nullable< double > AvgWind { get ; set ; } public string WindDir { get ; set ; } public Nullable< double > Visibility { get ; set ; } } |
JSON字符长度超出限制;
1 2 3 4 5 6 7 8 9 10 | <appSettings> <add key= "aspnet:MaxJsonDeserializerMembers" value= "150000000" /> </appSettings> <system.web.extensions> <scripting> <webServices> <jsonSerialization maxJsonLength= "2147483644" /> </webServices> </scripting> </system.web.extensions> |
未用上:HttpWebRequest方式比 WebClient功能更完善,更灵活,当然也更复杂。

/// <summary> /// 发送POST请求 /// </summary> /// <param name="url">请求URL</param> /// <param name="data">请求参数</param> /// <returns></returns> //static string HttpPost(string url, string data) //{ // HttpWebRequest httpWebRequest = (HttpWebRequest)HttpWebRequest.Create(url); // //字符串转换为字节码 // byte[] bs = Encoding.UTF8.GetBytes(data); // //参数类型,这里是json类型 // //还有别的类型如"application/x-www-form-urlencoded",不过我没用过(逃 // httpWebRequest.ContentType = "application/json"; // //参数数据长度 // httpWebRequest.ContentLength = bs.Length; // //设置请求类型 // httpWebRequest.Method = "POST"; // //设置超时时间 // httpWebRequest.Timeout = 20000; // //将参数写入请求地址中 // httpWebRequest.GetRequestStream().Write(bs, 0, bs.Length); // //发送请求 // HttpWebResponse httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse(); // //读取返回数据 // StreamReader streamReader = new StreamReader(httpWebResponse.GetResponseStream(), Encoding.UTF8); // string responseContent = streamReader.ReadToEnd(); // streamReader.Close(); // httpWebResponse.Close(); // httpWebRequest.Abort(); // return responseContent; //} ///// <summary> ///// 发送GET请求 ///// </summary> ///// <param name="url">请求URL,如果需要传参,在URL末尾加上“?+参数名=参数值”即可</param> ///// <returns></returns> //static string HttpGet(string url) //{ // //创建 // HttpWebRequest httpWebRequest = (HttpWebRequest)HttpWebRequest.Create(url); // //设置请求方法 // httpWebRequest.Method = "GET"; // //请求超时时间 // httpWebRequest.Timeout = 20000; // //发送请求 // HttpWebResponse httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse(); // //利用Stream流读取返回数据 // StreamReader streamReader = new StreamReader(httpWebResponse.GetResponseStream(), Encoding.UTF8); // //获得最终数据,一般是json // string responseContent = streamReader.ReadToEnd(); // streamReader.Close(); // httpWebResponse.Close(); // return responseContent; //}
加密部分省略。
1、不需要保密的数据,就加密一下 token 或 自定义的用户名、密码; 一般采用不可逆的MD5加密。
2、需要保密的数据:采用可逆的:RSA或AES加密 https://blog.csdn.net/huanhuanq1209/article/details/80614271
参考文档:
https://blog.csdn.net/rztyfx/article/details/110247593
https://q.cnblogs.com/q/98826/
http://www.ruanyifeng.com/blog/2014/02/ssl_tls.html
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
2018-01-26 sqlserver 删除表中数据 id 从1开始