HttpWebRequest WebClient给远程服务器上传数据; 未能创建 SSL/TLS 安全通道;JSON字符长度超出限制;

 

未能创建 SSL/TLS 安全通道,添加两句:

ServicePointManager.ServerCertificateValidationCallback += (s, cert, chain, sslPolicyErrors) => true;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;

 

WebClient给远程服务器上传数据

        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 控制器接收数据

        [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;
        }

数据接收类

    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字符长度超出限制;

  <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;
        //}
View Code

 

加密部分省略。

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

 

posted @ 2022-01-26 15:45  hao_1234_1234  阅读(170)  评论(0编辑  收藏  举报