以下面的GetXMLInfo接口为例:
C#调用WebService接口,我这采用的是拼接SOAP的请求和相应。完整代码如下:
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
namespace WindowsFormsApplication
{
class SoapUtil
{
private OnSoapBack soapback = null;
private static SoapUtil soapUtil = null;
private static readonly object objlock = new object();
SoapUtil()
{
}
//多线程下的单例模式
public static SoapUtil getInstance()
{
if (soapUtil == null)
{
lock (objlock)
{
if (soapUtil == null)
{
soapUtil = new SoapUtil();
}
}
}
return soapUtil;
}
public void GetSOAPReSource(String soapName, Dictionary<string,string> dic)
{
try
{
StringBuilder soapBuilder = new StringBuilder();
soapBuilder.Append("<?xml version=\"1.0\" encoding=\"utf - 8\"?>");
soapBuilder.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/\">");
soapBuilder.Append("<soap:Body>");
soapBuilder.Append("<" + soapName + " xmlns =\"http://tempuri.org/\">");
ICollection key = dic.Keys;
foreach (string k in key)
{
soapBuilder.Append("<" + k + ">").Append(dic[k]).Append("</" + k + ">");
}
soapBuilder.Append("</" + soapName + ">");
soapBuilder.Append("</soap:Body>");
soapBuilder.Append("</soap:Envelope>");
string url = "http://XXX.asmx";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "POST";
request.ContentType = "text/xml; charset=utf-8";
request.Timeout = 5000;
using (Stream reqStream = request.GetRequestStream())
{
byte[] paramBytes = Encoding.UTF8.GetBytes(soapBuilder.ToString());
reqStream.Write(paramBytes, 0, paramBytes.Length);
}
WebResponse webResponse = request.GetResponse();
using (StreamReader myStreamReader = new StreamReader(webResponse.GetResponseStream(), Encoding.UTF8))
{
//在这里对接收到的页面内容进行处理
if (soapback!=null) {
soapback.sucess(myStreamReader.ReadToEnd());
}
}
}
catch (Exception e)
{
Console.WriteLine("==========" + e.ToString());
}
}
public void setSoapBack(OnSoapBack soapback)
{
this.soapback = soapback;
}
}
interface OnSoapBack {
void sucess(string back);
void failure();
}
}
调用方式:
1、类继承OnSoapBack接口
2、实现接口 SoapUtil.getInstance().setSoapBack(this);
3、调用
Dictionary<string,string> dic = new Dictionary<string, string>();
dic.Add("Name", "app_doctor_config");
SoapUtil.getInstance().GetSOAPReSource("GetXMLInfo", dic); //(接口名称,接口入参)