调用WebService获取数据
以下调用方法,以调用苏州天气接口为例。
一、后台请求服务
方法一、C#后台,通过构建Soap请求接口数据
//获取天气详细信息 public JsonResult GetWeatherDetails(string dataType,string cityName) { //构造soap请求信息 StringBuilder soap = new StringBuilder(); soap.Append("<?xml version=\"1.0\" encoding=\"utf-8\"?>"); soap.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/\">"); soap.Append("<soap:Body>"); if (cityName != null) { soap.Append("<" + dataType + " xmlns =\"http://www.sz121.com/opapi\">"); soap.Append("<str>" + cityName + "</str>"); soap.Append("<sid></sid>"); soap.Append("</" + dataType + ">"); } else { soap.Append("<" + dataType + " xmlns =\"http://www.sz121.com/opapi\" />"); } soap.Append("</soap:Body>"); soap.Append("</soap:Envelope>"); //发起请求 Uri uri = new Uri("http://www.sz121.com/qxj/webservice/opapi.asmx"); WebRequest webRequest = WebRequest.Create(uri); webRequest.ContentType = "text/xml; charset=utf-8"; webRequest.Method = "POST"; using (Stream requestStream = webRequest.GetRequestStream()) { byte[] paramBytes = Encoding.UTF8.GetBytes(soap.ToString()); requestStream.Write(paramBytes, 0, paramBytes.Length); } //响应 string strWebData = string.Empty; WebResponse webResponse = webRequest.GetResponse(); using (StreamReader myStreamReader = new StreamReader(webResponse.GetResponseStream(), Encoding.UTF8)) { strWebData = myStreamReader.ReadToEnd(); } var results = new { result = strWebData, }; return Json(results, JsonRequestBehavior.AllowGet); }
方法二、直接使用VS添加服务引用
① 右击项目 添加服务引用
②点击高级
③添加Web引用
④输入url地址,修改web引用名,点击添加引用
⑤调用代码
public string getWeather() { com.sz121.www.WeatherWebService s = new com.sz121.www.WeatherWebService(); string CityName = "苏州"; string result = s.getWeatherbyCityName(CityName); return result.ToString(); }
二、前端进行解析
function loadXML(xmlString) { var xmlDoc = null; //判断浏览器的类型 //支持IE浏览器 if (!window.DOMParser && window.ActiveXObject) { //window.DOMParser 判断是否是非ie浏览器 var xmlDomVersions = ['MSXML.2.DOMDocument.6.0', 'MSXML.2.DOMDocument.3.0', 'Microsoft.XMLDOM']; for (var i = 0; i < xmlDomVersions.length; i++) { try { xmlDoc = new ActiveXObject(xmlDomVersions[i]); xmlDoc.async = false; xmlDoc.loadXML(xmlString); //loadXML方法载入xml字符串 break; } catch (e) { } } } //支持Mozilla浏览器 else if (window.DOMParser && document.implementation && document.implementation.createDocument) { try { /* DOMParser 对象解析 XML 文本并返回一个 XML Document 对象。 * 要使用 DOMParser,使用不带参数的构造函数来实例化它,然后调用其 parseFromString() 方法 * parseFromString(text, contentType) 参数text:要解析的 XML 标记 参数contentType文本的内容类型 * 可能是 "text/xml" 、"application/xml" 或 "application/xhtml+xml" 中的一个。注意,不支持 "text/html"。 */ domParser = new DOMParser(); xmlDoc = domParser.parseFromString(xmlString, 'text/xml'); } catch (e) { } } else { return null; } return xmlDoc; },
版权声明:本文为sharealex原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。