相同点:接口无非就是拼接字符串发动到指定的网站
参数既可以写到url中也可以写到body中
参考:
Get: 将传递参数写到url (http://localhost:8080/axis2/services/AAAA/getVerifyCode?args0=abc)
public class WebService_Url
{
/// <summary>
/// 需要WebService支持Get调用
/// </summary>
public string QueryGetWebService(string URL, string MethodName, Hashtable Pars)
{
//URl 最好指定IP地址访问否则会出现首次访问缓慢情况
string detilurl = URL + "/" + MethodName + "?" + ParsToString(Pars);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(detilurl);
request.Method = "GET";
//request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.Credentials = CredentialCache.DefaultCredentials;
request.Timeout = 10000;
request.Proxy=null;
try
{
return ReadXmlResponseString(request.GetResponse());
}
catch (Exception ex)
{
return "NG:"+ex.ToString();
}
}
/// <summary>
/// 针对信息解读(根据实际调整)
/// </summary>
public string GetReturnInnerMsg(string jsonStr)
{
XmlDocument doc = new XmlDocument();
doc.LoadXml(jsonStr);
XmlNamespaceManager xmlnsManager = new XmlNamespaceManager(doc.NameTable);
xmlnsManager.AddNamespace("ns", "http://wserver");
XmlNode returnNode = doc.SelectSingleNode("//ns:return", xmlnsManager);
if (returnNode != null)
{
if (returnNode.InnerText.Contains(":"))
{
return returnNode.InnerText.Replace(" ","").Split(':')[1];
}
return returnNode.InnerText;
}
else
{
return "";
}
}
/// <summary>
/// 将Hashtable转换成WEB请求键值对字符串
/// </summary>
/// <param name="Pars"></param>
/// <returns></returns>
private string ParsToString(Hashtable Pars)
{
StringBuilder sb = new StringBuilder();
foreach (string k in Pars.Keys)
{
if (sb.Length > 0)
{
sb.Append("&");
}
// sb.Append(HttpUtility.UrlEncode(k) + "=" + HttpUtility.UrlEncode(Pars[k].ToString()));
sb.Append(k+ "=" +Pars[k].ToString());
}
return sb.ToString();
}
private string ReadXmlResponseString(WebResponse response)
{
StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
string retXml = sr.ReadToEnd();
sr.Close();
return retXml;
}
}
使用方法
WebService_Url webServiceHelper = new WebService_Url();
string url = "http://localhost:8080/axis2/services/AAAA";
Hashtable ht = new Hashtable(); //创建一个Hashtable实例
//正式库
ht.Add("args0", "abc");
//发送数据
string msg = webServiceHelper.QueryGetWebService(url, "getVerifyCode", ht);
if (msg.Substring(0, 2)=="NG")
{
MessageForm mf = new MessageForm("总成,加密接口通信异常!", msg, true);
mf.ShowDialog();
return;
}
else
{
}
Post:将参数写到body中 (http://localhost:8080/axis2/services/AAAA/getVerifyCode)
public class WebService_Data
{
/// <summary>
/// 需要WebService支持Post调用
/// </summary>
public RemoteResult CreateTask(string url, CreateTaskParam pars)
{
var jsonFomat = new JsonSerializerSettings
{
ContractResolver = new CamelCasePropertyNamesContractResolver()
};
string postData = JsonConvert.SerializeObject(pars, Formatting.None, jsonFomat);
byte[] dataArray = Encoding.Default.GetBytes(postData);
//URl 最好指定IP地址访问否则会出现首次访问缓慢情况
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url+"/createTask");
//request.Method = "GET";
request.Method = "POST";
request.ContentType = "application/json";
request.ContentLength = dataArray.Length;
request.Timeout = 3000;
request.Proxy=null;
Stream dataStream = null;
try
{
dataStream = request.GetRequestStream();
}
catch (Exception ex)
{
RemoteResult remoteResult = new RemoteResult("999", ex.Message);
return remoteResult;
}
//发送请求
dataStream.Write(dataArray, 0, dataArray.Length);
dataStream.Close();
// Get response
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
StreamReader reader = new StreamReader(response.GetResponseStream());
string s = reader.ReadToEnd();
string result = HttpUtility.UrlDecode(s);
return JSONParse_Normal(result);
}
}
[DataContract]
public class RemoteResult
{
/// <summary>
/// 200:接收成功
/// 201:提升机运行中
/// 403:校验失败
/// 999:异常
/// </summary>
[DataMember(Order = 0)]
public string code { get; set; }
[DataMember(Order = 1)]
public string msg { get; set; }
public RemoteResult(string _code, string _msg)
{
code = _code;
msg = _msg;
}
}
private RemoteResult JSONParse_Normal(string result)
{
using (var ms = new MemoryStream(Encoding.Default.GetBytes(result)))
{
return (RemoteResult)new DataContractJsonSerializer(typeof(RemoteResult)).ReadObject(ms);
}
}
}
//2.PC任务创建
[DataContract]
public class CreateTaskParam
{
/// <summary>
/// 任务id
/// </summary>
[DataMember]
public string taskId { get; set; }
/// <summary>
/// 仓库标识
/// </summary>
[DataMember]
public string warehouseCode { get; set; }
/// <summary>
/// in:入库 out:出库 move:移库 changeLayer: 空车换层
/// </summary>
[DataMember]
public string taskType { get; set; }
/// <summary>
/// 容器编号
/// </summary>
[DataMember]
public string containerCode { get; set; }
/// <summary>
/// 任务起点
/// </summary>
[DataMember]
public string start { get; set; }
/// <summary>
/// 任务终点
/// </summary>
[DataMember]
public string end { get; set; }
/// <summary>
/// 扩展项目不可用
/// </summary>
[DataMember]
public string parameters { get; set; }
/// <summary>
/// 任务下发时间
/// </summary>
[DataMember]
public string taskSendTime { get; set; }
/// <summary>
/// 任务优先级 1-5(优先级递增)
/// </summary>
[DataMember]
public string priority { get; set; }
}
使用方法:
string url = "http://localhost:8080/axis2/services/AAAA";
CreateTaskParam createTaskParam = new CreateTaskParam();
createTaskParam.start="A01";
createTaskParam.end="B01";
WebService_Data webService_Data = new WebService_Data();
RemoteResult remoteResult = webService_Data.CreateTask(url, createTaskParam);
if (remoteResult.code=="999")
{
}
else
{
}
--------------------------------------以上结束, 以下参考-----------------------------------------------------------
?wsdl格式 转换成GET方式参考:
-------------------------------------------------------------------------------------------------
-------------------------------------------------------------
天气的测试地址
WeatherWebService Web 服务http://www.webxml.com.cn/WebServices/WeatherWebService.asmxwsdl
http://www.webxml.com.cn/WebServices/WeatherWebService.asmx?wsdl
转换后:
http://www.webxml.com.cn/WebServices/WeatherWebService.asmx/getSupportCity?byProvinceName=上海
-----------------------------------------------------------------------------------------------------------
方法二(不推荐):
/* 调用方式
* string url = "http://www.webservicex.net/globalweather.asmx" ;
* string[] args = new string[2] ;
* args[0] = "Hangzhou";
* args[1] = "China" ;
* object result = WebServiceHelper.InvokeWebService(url ,"GetWeather" ,args) ;
* Response.Write(result.ToString());
*/
class WebServiceHelper
{
#region InvokeWebService
/// <summary>
/// 动态调用web服务
/// </summary>
/// <param name="url">WSDL服务地址</param>
/// <param name="methodname">方法名</param>
/// <param name="args">参数</param>
/// <returns></returns>
public static object InvokeWebService(string url, string methodname, object[] args)
{
return WebServiceHelper.InvokeWebService(url, null, methodname, args);
}
/// <summary>
/// 动态调用web服务
/// </summary>
/// <param name="url">WSDL服务地址</param>
/// <param name="classname">类名</param>
/// <param name="methodname">方法名</param>
/// <param name="args">参数</param>
/// <returns></returns>
public static object InvokeWebService(string url, string classname, string methodname, object[] args)
{
string @namespace = "EnterpriseServerBase.WebService.DynamicWebCalling";
if ((classname == null) || (classname == ""))
{
classname = WebServiceHelper.GetWsClassName(url);
}
try
{
//获取WSDL
WebClient wc = new WebClient();
Stream stream = wc.OpenRead(url + "?WSDL");
ServiceDescription sd = ServiceDescription.Read(stream);
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)
{
System.Text.StringBuilder sb = new System.Text.StringBuilder();
foreach (System.CodeDom.Compiler.CompilerError ce in cr.Errors)
{
sb.Append(ce.ToString());
sb.Append(System.Environment.NewLine);
}
throw new Exception(sb.ToString());
}
//生成代理实例,并调用方法
System.Reflection.Assembly assembly = cr.CompiledAssembly;
Type t = assembly.GetType(@namespace + "." + classname, true, true);
object obj = Activator.CreateInstance(t);
System.Reflection.MethodInfo mi = t.GetMethod(methodname);
return mi.Invoke(obj, args);
/*
PropertyInfo propertyInfo = type.GetProperty(propertyname);
return propertyInfo.GetValue(obj, null);
*/
}
catch (Exception ex)
{
throw new Exception(ex.InnerException.Message, new Exception(ex.InnerException.StackTrace));
}
}
private static string GetWsClassName(string wsUrl)
{
string[] parts = wsUrl.Split('/');
string[] pps = parts[parts.Length - 1].Split('.');
return pps[0];
}
#endregion
}
调用方法:
string url = "http://10.255.30.40:9003/LESPrepareDeliveryService.asmx";
//方法
string fuc = "getSpsMatDt";
//参数
string par = "3210;A1;NS001";
int Pcount = par.Split(';').Count() + 1;
//生成参数信息
string[] args = new string[Pcount];
for (int i = 0; i < Pcount - 1; i++)
{
args[i] = par.Split(';')[i];
}
args[Pcount - 1] = dtm;
//获取Webservice的数据信息
object result = WebServiceHelper.InvokeWebService(url, fuc, args);
DataTable dt = (DataTable)result;
return dt;