WebService的 http/soap调用 完整过程

调用

测试接口为 http://***/webservice/interOuterService/pushData

1.Http 调用接口(如果接口参数是复杂对象,该方法失效 例如数组)

    HttpClient client = new HttpClient();
    var jsonCon = "{receiveModelXml:\"" + xmlResult + "\"}";
    HttpContent httpContent = new StringContent(jsonCon, Encoding.UTF8, "application/json");
    var url = "http://***/webservice/interOuterService/pushData ";
    var Res = client.PostAsync(url, httpContent).Result;
    var sdssdasdaas = Res.Content.ReadAsStringAsync();

注意事项

1.参数中一定要写好入参名称,否则报错 参数未找到
2.如果接口需要的是xml文件。可以将xml转成string 然后以json传输(格式转换见)
3.如果ContentType采用 "application/x-www-form-urlencoded"形式的http请求(如果没问题 不需要修改)
需要对web.config文件进行修改,在<system.web>块内修改:
在这里插入图片描述

如果是运行时版本4.0, 添加下面一段内容即可(亲测)
<httpRuntime requestValidationMode="2.0"/>
如果仍有问题,继续修改
<webServices>
<protocols>
<add name="HttpPost"/>
<add name="HttpGet"/>
</protocols>
</webServices>

2.soap1.2协议的http请求(必须使用该方法的情况:接口需要传对象而不是字符串)

var param4 = "<soap:Envelope xmlns:soap=\"http://www.w3.org/2003/05/soap-envelope\" xmlns:tem=\"http://tempuri.org/\"><soap:Header/><soap:Body><tem:SyncIncrementOrgToI8Async><tem:models><tem:OrgModel><tem:OCode>qw</tem:OCode><tem:OCBo>21111Z</tem:OCBo><tem:OName>13</tem:OName><tem:OrgType>Y</tem:OrgType><tem:CBoo></tem:CBoo><tem:Bopomofo></tem:Bopomofo><tem:CodeValue></tem:CodeValue><tem:OMemo>13</tem:OMemo><tem:IsActive>Y</tem:IsActive><tem:InsertRelat>false</tem:InsertRelat><tem:ParentOCode></tem:ParentOCode><tem:AttrCode></tem:AttrCode></tem:OrgModel><tem:OrgModel><tem:OCode>123</tem:OCode><tem:OCBo>1122222</tem:OCBo><tem:OName>13</tem:OName><tem:OrgType>N</tem:OrgType><tem:CBoo>12Test</tem:CBoo><tem:Bopomofo></tem:Bopomofo><tem:CodeValue></tem:CodeValue><tem:OMemo>13</tem:OMemo><tem:IsActive>Y</tem:IsActive><tem:InsertRelat>false</tem:InsertRelat><tem:ParentOCode></tem:ParentOCode><tem:AttrCode></tem:AttrCode></tem:OrgModel></tem:models></tem:SyncIncrementOrgToI8Async></soap:Body></soap:Envelope>";

此处param4的 xmlns:tem=\"http://tempuri.org/\"> 中的tem 和报文主体内容的前缀一致,接口可以直接以报文对应的对象作为参数;
如果不想写前缀, 需要把报文内容以<![CDATA[xml数据]] 封装代替,此时,接口参数只能是字符串;

HttpClient + soap(soap中是xml格式的参数,接收参数是xml格式)该方法可以跨语言环境

HttpClient client = new HttpClient();
HttpContent httpContent = new StringContent(param4, Encoding.UTF8, "application/soap+xml");//param4是soap报文格式的数据
var url = "http://localhost:5144/OrgService.asmx";
var Res = client.PostAsync(url, httpContent).Result;
var sdssdasdaas = Res.Content.ReadAsStringAsync().Result;

返回值SOAP报文的值获取

XmlElement root = doc.DocumentElement
XmlNamespaceManager nsmgr = new XmlNamespaceManager(doc.NameTable);
nsmgr.AddNamespace("soap", "http://schemas.xmlsoap.org/soap/envelope/");
string value = doc.SelectSingleNode("//soap:Envelope", nsmgr).InnerText;

上面方法如果调用不通,可使用SOA查看接口的格式

上面截图需要进行这种代码编写

HttpContent httpContent = new StringContent(xmlResult, Encoding.UTF8, "text/xml");
            httpContent.Headers.Add("SOAPAction", "execute");
            var Res = client.PostAsync(scmZBUrl, httpContent).Result;

HttpClient+string
使用条件:取消服务类的注释 [System.Web.Script.Services.ScriptService]

        HttpClient client = new HttpClient();
        HttpContent httpContent = new StringContent("supplyModelJson=" + str, Encoding.UTF8, "application/x-www-form-urlencoded");
        var url = "http://localhost:6014/PurchaseReceive.asmx/SyncSupply";
        var Res = client.PostAsync(url, httpContent).Result;
        var sdssdasdaas = Res.Content.ReadAsStringAsync().Result;

HttpClient+json 请求方法的参数是对象
使用条件:取消服务类的注释 [System.Web.Script.Services.ScriptService]

        HttpClient client = new HttpClient();
        HttpContent httpContent = new StringContent("{\"models\":"+ param + "}", Encoding.UTF8, "application/json");
        var url = "http://localhost:5144/OrgService.asmx/SyncIncrementOrgToI8Async";
        var Res = client.PostAsync(url, httpContent).Result;
        var sdssdasdaas = Res.Content.ReadAsStringAsync().Result;

HttpWebRequest

var request = (HttpWebRequest)WebRequest.Create("http://localhost:5144/OrgService.asmx");
//不需要关联方法,方法在xml中指定
request.ContentType = "application/soap+xml;charset=UTF-8";
request.Method = "POST";
using (var streamWriter = new StreamWriter(request.GetRequestStream()))
{
    streamWriter.Write(param4);//param4是soap报文格式的字符串
}
var result = "";
var response = (HttpWebResponse)request.GetResponse();
 using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
 {
     result= reader.ReadToEnd();
 }

soap1.1 和 1.2 的区别主要表现在

区别 (1)
http头的 Content-Type: 字段
1.1的 Content-Type: text/xml; charset=utf-8
1.2的 Content-Type: application/soap+xml; charset=utf-8
区别(2)
http头的SOAPAction: 字段
1.1的要求有 SOAPAction: 字段,内容为 明明空间+方法名
1.2版本 不需要 SOAPAction: 字段
区别(3)
namespace不同
1.1版本的namespace 为 http://schemas.xmlsoap.org/soap/envelope/
1.2版本的namespace 为 http://www.w3.org/2003/05/soap-envelope
原文:https://blog.csdn.net/xiaofei125145/article/details/41351761

3.WebService 调用接口 只支持C# 如果和java对接 无法映射出对应的dll java是.jar格式文件

辅助类 WebServiceHelper

public class WebServiceHelper
    {
        public static object InvokeWebService(string url, string methodname, object[] args)
        {
            return WebServiceHelper.InvokeWebService(url, null, methodname, args);
        }

        private static object InvokeWebService(string url, string classname, string methodname, object[] args)
        {
            string @namespace = "client";
            if ((classname == null) || (classname == ""))
            {
                classname = WebServiceHelper.GetWsClassName(url);
            }
            try
            {
                WebClient wc = new WebClient();
                Stream stream = wc.OpenRead(url + "?WSDL");
                ServiceDescription sd = ServiceDescription.Read(stream);
                classname = sd.Services[0].Name;
                ServiceDescriptionImporter sdi = new ServiceDescriptionImporter();
                sdi.AddServiceDescription(sd, "", "");
                CodeNamespace cn = new CodeNamespace(@namespace);

                CodeCompileUnit ccu = new CodeCompileUnit();
                ccu.Namespaces.Add(cn);
                sdi.Import(cn, ccu);
                CSharpCodeProvider icc = new CSharpCodeProvider();
                CompilerParameters cplist = new CompilerParameters();
                cplist.GenerateExecutable = false;
                cplist.GenerateInMemory = true;
                cplist.ReferencedAssemblies.Add("System.dll");
                cplist.ReferencedAssemblies.Add("System.XML.dll");
                cplist.ReferencedAssemblies.Add("System.Web.Services.dll");
                cplist.ReferencedAssemblies.Add("System.Data.dll");

                CompilerResults cr = icc.CompileAssemblyFromDom(cplist, ccu);
                if (true == cr.Errors.HasErrors)
                {
                    StringBuilder sb = new StringBuilder();
                    foreach (CompilerError ce in cr.Errors)
                    {
                        sb.Append(ce.ToString());
                        sb.Append(System.Environment.NewLine);
                    }

                    throw new Exception(sb.ToString());
                }

                Assembly assembly = cr.CompiledAssembly;
                Type t = assembly.GetType(@namespace + "." + classname, true, true);
                object obj = Activator.CreateInstance(t);
                MethodInfo mi = t.GetMethod(methodname);
                return mi.Invoke(obj, args);
            }
            catch (Exception ex)
            {
                LogHelper<WebServiceHelper>.Error("调用接口异常:" + ex.Message);
                throw new Exception(ex.InnerException.Message, new Exception(ex.InnerException.StackTrace));
            }
        }

        private static string GetWsClassName(string url)
        {
            string[] parts = url.Split('/');
            string[] pps = parts[parts.Length - 1].Split('.');

            return pps[pps.Length - 1];
        }
    }

调用

    var serviceUrl = "http://***/webservice/interOuterService";
    object[] args = new object[2] { xmlResult, "0" };
    var sendResult = WebServiceHelper.InvokeWebService(serviceUrl, "pushData", args).ToString();

注意事项

1.一定要知道接口的参数数量,否则提示参数计数不匹配

发布了22 篇原创文章 · 获赞 0 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/Street_Walker/article/details/92842052