如何通过http的方式调用webservice

39 阅读1分钟

有个项目后端用的.net语言开发,之前调用第三方webservice都是用的添加服务引用的模式,感觉还挺好,将第三方url配置在web.config中,最近遇到个项目要求将url地址配置在系统参数,被迫来研究下通过http调用webservice。

1.构建soap请求XML

我是通过soapui来查看soap请求的,打开soapui,【file-New Soap Project】,然后输入IP地址,点击ok,即可看到soap请求。

2.具体实现代码

private static string CallWebService(string url, string data)
        {
            try
            {
                // 构建SOAP请求
                string soapRequest = $@"<?xml version=""1.0"" encoding=""utf-8""?>
                //具体的soap请求xml
                var soapXml="";
                soapRequest+=soapXml;

                // 创建HTTP请求
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
                request.Method = "POST";
                request.ContentType = "text/xml; charset=utf-8";
                request.Timeout = 600000; // 10分钟超时

                // 发送请求
                byte[] data = Encoding.UTF8.GetBytes(soapRequest);
                request.ContentLength = data.Length;

                using (Stream stream = request.GetRequestStream())
                {
                    stream.Write(data, 0, data.Length);
                }

                // 获取响应
                using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
                using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
                {
                    string responseText = reader.ReadToEnd();

                    // 简单提取XML内容(从<return>标签中)
                    int startIndex = responseText.IndexOf("<return>");
                    int endIndex = responseText.IndexOf("</return>");

                    if (startIndex >= 0 && endIndex > startIndex)
                    {
                        return responseText.Substring(startIndex + 8, endIndex - startIndex - 8);
                    }

                    return responseText;
                }
            }
            catch (Exception ex)
            {
                throw new Exception($"调用WebService失败: {ex.Message}", ex);
            }
        }