C#從OneNet獲取數據

C#實現窗體通過Request訪問到OneNet雲平臺,數據解析後展示在textbox中,並實現數據自動保存到MySQL數據表

private void button1_Click(object sender, EventArgs e)
        {
            string url = "http://api.heclouds.com/devices/*****/datapoints?";
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.Method = "GET";
            var property = typeof(WebHeaderCollection).GetProperty("InnerCollection",                             
            BindingFlags.Instance | BindingFlags.NonPublic);
            if (property != null)
            {
                var collection = property.GetValue(request.Headers, null) as NameValueCollection;
                collection["api-key"] = "*******";
            }
            request.Host = "api.heclouds.com";
            request.ProtocolVersion = new Version(1, 1);
            request.ContentType = "text/html;charset=UTF-8";
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            Stream myResponseStream = response.GetResponseStream();
            StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8"));
            string retString = myStreamReader.ReadToEnd();
            myStreamReader.Close();
            myResponseStream.Close();
            string temp = retString.Substring(99, 2);
            textBox1.Text = temp;
            string humi = retString.Substring(170, 1);
            textBox2.Text = humi;
            string beam = retString.Substring(240, 1);
            textBox3.Text = beam;
            string dateTime;
            dateTime = DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss.fff");
            textBox4.Text = dateTime;
            string str = "data source=localhost;database=air;user id=root;password=123456;pooling=false;charset=utf8";
            MySqlConnection conn = new MySqlConnection(str);
            conn.Open();
            //數據插入MySQL數據表
            string sql = "Insert into air_value (temp,humi,beam,time) values ('" + temp + "','" + humi + "','" + beam + "','" + dateTime + "')";
            MySqlCommand cmd = new MySqlCommand(sql, conn);
            cmd.CommandType = CommandType.Text;
            MySqlDataReader sdr;
            sdr = cmd.ExecuteReader();
        
        }

參考鏈接: https://www.cnblogs.com/luxiaoguogege/p/10142053.html 

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