之前做的一個項目當中要向網站發送請求,然后網站返回給我一個Json格式的數據,對Json格式數據進行處理
請求方法如下
public string GetPage(string requestUrl) { Stream instream = null; StreamReader sr = null; HttpWebResponse response = null; HttpWebRequest request = null; // 准備請求... try { // 設置參數 request = WebRequest.Create(requestUrl) as HttpWebRequest; CookieContainer cookieContainer = new CookieContainer(); request.CookieContainer = cookieContainer; request.AllowAutoRedirect = true; request.Method = "GET"; //請求方式GET或POST request.ContentType = "application/x-www-form-urlencoded"; request.Headers.Add("Authorization", "Basic YWRtaW46YWRtaW4="); //發送請求並獲取相應回應數據 response = request.GetResponse() as HttpWebResponse; //直到request.GetResponse()程序才開始向目標網頁發送Post請求 instream = response.GetResponseStream(); sr = new StreamReader(instream, Encoding.UTF8); //返回結果網頁(html)代碼 string content = sr.ReadToEnd(); string err = string.Empty; return content; } catch (Exception ex) { Log.LogError(ex); MessageBox.Show(ex.Message, "服務連接", MessageBoxButtons.OK, MessageBoxIcon.Error); return ""; } }
參數requestUrl為請求的地址,返回為string類型
下面是示例演示,調用GetPage方法,返回的字符串格式是Json類型的,我這里把這個格式轉換成了PersonChronicDisease這個對象以便在項目中使用
string response=GetPage(http://xxxx);
PersonChronicDisease pcd=JsonConvert.DeserializeObject(response, typeof(PersonChronicDisease)) as PersonChronicDisease;
JsonConvert在Newtonsoft.Json命名空間下,所以我們要添加Newtonsoft.Json.dll
大家有什么不懂的,可以在下面留言
