很早之前调用WebService接口都是在项目中引用服务,然后new实例直接调用,但是第三方提供的是java的WebService,还有就是接口地址需要配置在表中,对接了两次都折腾了好些时间,记录一下吧,万变不离其宗,还是用的HttpClient
先使用SoapUI生成请求报文
然后是用HttpClient调用接口并解析结果
public async Task<string> PostAsync(string reqUrl, HttpContent httpContent)
{
using HttpClient httpClient = _httpClientFactory.CreateClient();
using HttpResponseMessage httpResponseMessage = await httpClient.PostAsync(reqUrl, httpContent);
httpResponseMessage.EnsureSuccessStatusCode();
return await httpResponseMessage.Content.ReadAsStringAsync();
}
try
{
string Url = await this._appSettingService.GetAppSettingKeyValue("Url");
string xml = "";
xml += "<soap:Envelope xmlns:soap=\"http://www.w3.org/2003/05/soap-envelope\" xmlns:ser=\"http://service.dxd.com/\">";
xml += " <soap:Header/>";
xml += " <soap:Body>";
xml += " <ser:inParam>" + request.InParam + "</ser:inParam>";
xml += " </soap:Body>";
xml += "</soap:Envelope>";
HttpContent httpContent = new StringContent(xml, Encoding.UTF8, "text/xml");
string outXml = await this._webServiceClient.PostAsync(Url, httpContent);
Match match = Regex.Match(outXml, @"<soap:Envelope.*?>(.*?)</soap:Envelope>");
if (match.Success)
{
XmlDocument xmlDocument = new XmlDocument();
xmlDocument.LoadXml(match.Value);
XmlNamespaceManager nsmgr = new XmlNamespaceManager(xmlDocument.NameTable);
nsmgr.AddNamespace("soap", "http://www.w3.org/2003/05/soap-envelope");
nsmgr.AddNamespace("svc", "http://service.dxd.com/");
XmlNode? bodyNode = xmlDocument.SelectSingleNode("//soap:Envelope/soap:Body", nsmgr);
if (bodyNode != null)
{
XmlNode? returnCallNode = bodyNode.SelectSingleNode("svc:returnCall", nsmgr);
if (returnCallNode != null)
{
JObject objResult = JObject.Parse(returnCallNode.InnerText);
if (objResult.Value<int>("success") == 1)
{
resp.Data = objResult.Value<string>("outParam");
}
else
{
resp.Data = objResult.Value<string>("outParam");
}
resp.Succ("获取成功!");
}
else
{
throw new AppException(bodyNode.InnerText);
}
}
}
}
catch (Exception ex)
{
resp.Fail("获取失败!" + ex.Message);
}