C#、.Net通过HttpWebRequest请求WebService接口

C#调用WebService有三种方式,静态调用、动态调用、Http访问,今天我们要实现的HttpWebRequest来调用WebService。
首先,需要在HttpWebRequest上面加一个SOAP格式内容,参数为:xml,修改对应的请求方法及命名中间地址、请求参数名,这三个非常重要,对应你要访问的WebService地址中都有的,具体看图中圈中的地方。

如果部署在内网不方便测试的情况,可以访问http://www.webxml.com.cn/zh_cn/web_services.aspx来测试。
具体实现代码如下:

 /// <summary>
 /// 测试按钮中调用WebService接口
 /// </summary>
 /// <param name="sender"></param>
 /// <param name="e"></param>
 private void button1_Click(object sender, EventArgs e)
 {
     //string result = HttpPostWebService(textBox1.Text, textBox2.Text);
     string result = HttpPostWebService("http://localhost:5000/StudentService.asmx", "<strInput>192.168.1.100</strInput>");
     MessageBox.Show(result);
 }

 /// <summary>
 /// 调用WebService接口
 /// </summary>
 /// <param name="url">请求接口地址</param>
 /// <param name="strInput"></param>
 /// <returns></returns>
 public string HttpPostWebService(string url, string strInput)
 {
     string result = string.Empty;//返回值
     //string param = string.Empty;//请求参数
     byte[] bytes = null;
     HttpWebRequest request = null;
     Stream writer = null;
     string responseString = string.Empty;//返回内容
     // SOAP格式内容,参数为:xml
     StringBuilder param = new StringBuilder();
     param.Append("<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">\r\n");
     param.Append("<soap:Body>\r\n");
     param.Append("<Get xmlns=\"http://tempuri.org/\">\r\n");//请求方法名称
     param.Append("<strInput>测试</strInput>");//请求参数
     param.Append("</Get>\r\n</soap:Body>\r\n</soap:Envelope>");
     try
     {
         //param = $"strInput={strInput}";//接收参数名称
         bytes = Encoding.UTF8.GetBytes(param.ToString());
         request = (HttpWebRequest)WebRequest.Create(url);
         request.Method = "POST";
         request.ContentType = "text/xml;charset=UTF-8";
         request.ContentLength = bytes.Length;
         request.Timeout = 10000; // 设置请求超时时间为10秒
         using (writer = request.GetRequestStream())
         {
             writer.Write(bytes, 0, bytes.Length);
         }
         using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
         {
             using (StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
             {
                 result = sr.ReadToEnd();
             }
         }
     }
     catch (Exception ex)
     {
         throw ex;
     }
     return result;
 }
` demo源码:https://github.com/cplmlm/LearningProjectsForm
posted on 2024-06-11 11:58  一只小小的程序猿  阅读(218)  评论(0编辑  收藏  举报