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

  • 6
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值