C#winfrom调用webService接口(地址:http://10.10.47.132:8103/soap/IWebService))传值并接收返回值,实现代码 接口地址可以在文件配置更改
时间: 2024-02-03 09:03:57 浏览: 29
你可以使用C#的`HttpClient`类来调用WebService接口,并传递参数和接收返回值。以下是一个示例代码:
```csharp
using System;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
namespace WebServiceExample
{
class Program
{
static async Task Main(string[] args)
{
// 接口地址
string url = "http://10.10.47.132:8103/soap/IWebService";
// 创建HttpClient对象
HttpClient client = new HttpClient();
// 创建SOAP请求内容
string soapRequest = @"<?xml version=""1.0"" encoding=""utf-8""?>
<soap:Envelope xmlns:soap=""http://schemas.xmlsoap.org/soap/envelope/"">
<soap:Body>
<YourMethodName xmlns=""YourNamespace"">
<Param1>Value1</Param1>
<Param2>Value2</Param2>
</YourMethodName>
</soap:Body>
</soap:Envelope>";
// 设置请求头部信息
client.DefaultRequestHeaders.Add("SOAPAction", "YourSOAPAction");
// 发送请求并获取响应
HttpResponseMessage response = await client.PostAsync(url, new StringContent(soapRequest, Encoding.UTF8, "text/xml"));
// 读取响应内容
string responseContent = await response.Content.ReadAsStringAsync();
// 解析XML响应
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml(responseContent);
// 提取返回值
XmlNamespaceManager nsManager = new XmlNamespaceManager(xmlDoc.NameTable);
nsManager.AddNamespace("soap", "http://schemas.xmlsoap.org/soap/envelope/");
nsManager.AddNamespace("ns", "YourNamespace");
XmlNode resultNode = xmlDoc.SelectSingleNode("//ns:YourMethodNameResponse/ns:YourMethodNameResult", nsManager);
string result = resultNode.InnerText;
// 输出返回值
Console.WriteLine("返回值: " + result);
}
}
}
```
你需要将上述代码中的以下部分进行替换:
- `url`:将其替换为你的WebService接口地址。
- `soapRequest`:将其替换为你的SOAP请求内容。
- `"YourMethodName"`:将其替换为你要调用的WebService方法名。
- `"YourNamespace"`:将其替换为你的命名空间。
- `"YourSOAPAction"`:将其替换为你的SOAPAction。
请确保你的应用程序具有访问WebService接口的权限,并根据实际情况修改代码以适应你的需求。