c# winform 訪問WebServices (通過Http Post方式)

  • 2020 年 3 月 26 日
  • 筆記

第一步、編寫WebServices服務方法

 1         [WebMethod]   2         public void PostJson(string str, string bb)   3         {   4             Dictionary<string, object> DictResult = new Dictionary<string, object>();   5             IList<Dictionary<string, string>> list = new List<Dictionary<string, string>>();   6             /*此處提供的只是示例,實際項目中,按照具體業務*/   7             for (int ii = 0; ii < 5; ii++)   8             {   9                 Dictionary<string, string> dict = new Dictionary<string, string>();  10                 dict.Add("str", str);  11                 dict.Add("bb", bb);  12                 list.Add(dict);  13             }  14             /*此處提供的只是示例,實際項目中,按照具體業務*/  15             if (str == "11")  16             {  17                 DictResult.Add("Code", "0");  18                 DictResult.Add("Msg", "訪問成功");  19                 DictResult.Add("Result", list);  20             }  21             else  22             {  23                 DictResult.Add("Code", "-1");  24                 DictResult.Add("Msg", "訪問失敗");  25                 DictResult.Add("Result", null);  26             }  27  28             Tools.ConvertToJson(DictResult);  29         }

Web方法返回的內容

 

 

 第二步、編寫Winform客戶端的訪問程式碼

 1  string HttpPost(string URL, string Para)   2         {   3             // 創建HttpWebRequest對象   4             HttpWebRequest httpRequest = (HttpWebRequest)WebRequest.Create(URL);   5             httpRequest.Method = "POST";   6             httpRequest.ContentType = "application/x-www-form-urlencoded";   7             byte[] bytes = Encoding.UTF8.GetBytes(Para);   8             using (Stream reqStream = httpRequest.GetRequestStream())   9             {  10                 reqStream.Write(bytes, 0, bytes.Length);  11                 reqStream.Flush();  12             }  13             try  14             {  15                 using (HttpWebResponse myResponse = (HttpWebResponse)httpRequest.GetResponse())  16                 {  17                     StreamReader sr = new StreamReader(myResponse.GetResponseStream(), Encoding.UTF8);  18                     string responseString = sr.ReadToEnd();  19                     return responseString;  20                 }  21             }  22             catch (WebException webex)  23             {  24                 var res = (HttpWebResponse)webex.Response;  25                 StreamReader sr = new StreamReader(res.GetResponseStream(), Encoding.UTF8);  26                 string str = sr.ReadToEnd();  27                 return str;  28             }  29         }

第三步、設計調用介面

 

 

 

第四步、執行調用方法

1   private void button1_Click(object sender, EventArgs e)  2         {  3             string url = "http://localhost:6029/TestServ.asmx/PostJson";  4             string Para = "str=11&bb=AA";  5             textBox1.Text = HttpPost(url, Para);  6         }

第五步、顯示執行結果