第一步, 编写 webServices 服务方法
- [WebMethod]
- public void PostJson(string str, string bb)
- {
- Dictionary<string, object> DictResult = new Dictionary<string, object>();
- IList<Dictionary<string, string>> list = new List<Dictionary<string, string>>();
- /* 此处提供的只是示例, 实际项目中, 按照具体业务 */
- for (int ii = 0; ii <5; ii++)
- {
- Dictionary<string, string> dict = new Dictionary<string, string>();
- dict.Add("str", str);
- dict.Add("bb", bb);
- list.Add(dict);
- }
- /* 此处提供的只是示例, 实际项目中, 按照具体业务 */
- if (str == "11")
- {
- DictResult.Add("Code", "0");
- DictResult.Add("Msg", "访问成功");
- DictResult.Add("Result", list);
- }
- else
- {
- DictResult.Add("Code", "-1");
- DictResult.Add("Msg", "访问失败");
- DictResult.Add("Result", null);
- }
- Tools.ConvertToJson(DictResult);
- }
Web 方法返回的内容
第二步, 编写 Winform 客户端的访问代码
- string HttpPost(string URL, string Para)
- {
- // 创建 HttpWebRequest 对象
- HttpWebRequest httpRequest = (HttpWebRequest)WebRequest.Create(URL);
- httpRequest.Method = "POST";
- httpRequest.ContentType = "application/x-www-form-urlencoded";
- byte[] bytes = Encoding.UTF8.GetBytes(Para);
- using (Stream reqStream = httpRequest.GetRequestStream())
- {
- reqStream.Write(bytes, 0, bytes.Length);
- reqStream.Flush();
- }
- try
- {
- using (HttpWebResponse myResponse = (HttpWebResponse)httpRequest.GetResponse())
- {
- StreamReader sr = new StreamReader(myResponse.GetResponseStream(), Encoding.UTF8);
- string responseString = sr.ReadToEnd();
- return responseString;
- }
- }
- catch (WebException webex)
- {
- var res = (HttpWebResponse)webex.Response;
- StreamReader sr = new StreamReader(res.GetResponseStream(), Encoding.UTF8);
- string str = sr.ReadToEnd();
- return str;
- }
- }
第三步, 设计调用界面
第四步, 执行调用方法
- private void button1_Click(object sender, EventArgs e)
- {
- string url = "http://localhost:6029/TestServ.asmx/PostJson";
- string Para = "str=11&bb=AA";
- textBox1.Text = HttpPost(url, Para);
- }
第五步, 显示执行结果
来源: https://www.cnblogs.com/lzsin/p/12577674.html