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

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章