在winform中,如果要获取别人的开放的api或者是访问外部网路数据,都需要建立http链接,然后通过post/get方法来获取数据,然后反序列化,将获取的数据赋值到已建立好的model里来,从而在窗口来展示;
////// 建立http链接方法 /// /// 通过输入框或者是默认的链接地址 public string SetHttpLink(string apiUrl ) { HttpWebRequest request; request = (HttpWebRequest)WebRequest.Create(apiUrl); HttpWebResponse response; response = (HttpWebResponse)request.GetResponse(); //get方法 System.IO.StreamReader reader = new StreamReader(response.GetResponseStream(),Encoding.UTF8); string reponseTxt = reader.ReadToEnd(); reader.Close(); return reponseTxt; }
反序列化:反序列化有三种方法,引用的介绍
////// 按照歌名搜索按钮事件 /// /// /// private void toolStripButton7_Click(object sender, EventArgs e) { string ReacherMusicListHttp; string textboxurl; textboxurl = toolStripButton6.Text; if (string.IsNullOrEmpty(textboxurl)) { MessageBox.Show("请输入歌曲名字!"); } else { string pinjiezifu = string.Format("?format=json&method=baidu.ting.search.catalogSug&query={0}", textboxurl); ReacherMusicListHttp = string.Format("http://tingapi.ting.baidu.com/v1/restserver/ting" + pinjiezifu); string result= SetHttpLink(ReacherMusicListHttp); SelectSongListModel descJsonStu = JsonConvert.DeserializeObject(result);//反序列化 //string messate = string.Format("反序列化: ID={0},Name={1}", descJsonStu.song, descJsonStu.order); List list = descJsonStu.song.ToList(); //这里还需要加个空值判断 foreach (var onesong in list) { listBox1.Items.Add(onesong.songName + " _ " + onesong.artistname) ; selectsongNamelist.Add(onesong.songName+" _ "+onesong.artistname); selectsongIdlist.Add(onesong.songid); } } }