.net 调用webservice
1、调用webserivice 最简单的方法就是在 "引用" 那里点击右键,然后选择"引用web服务",再输入服务地址。确定后,会生成一个app.config 里面就会自动生成了一些配置信息,配置信息是一个代理类,通过初始化代理类 使用代理类的方法调用 跟普通类调用一样
2、get/post动态调用
注意
1、在使用的时候 webservice 呢如果返回是dataset类型 尽量不要直接返回 因为包含很多不需要的头信息 增加负载,可以使用.getxml()方法进行 对dataset中不必要的头和复杂信息简化 减少负载。 使用dataset 使用数据空间可以直接绑定返回值
2、在ssystem web配置下增加配置《protocol》节点
<system.web> <webServices> <protocols> <add name="HttpGet" /> <add name="HttpPost"/> </protocols> </webServices>否则webservice不支持get和post调用方式
(1)get方法调用 ?参数名=参数值 (传参)
public class WebServiceHelper
{
public static string CallServiceByGet(string strURL)
{
//string strURL = "http://localhost:12074/Service1.asmx/GetProductPrice?ProductId=";
//strURL += this.textBox1.Text;
//创建一个HTTP请求
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(strURL);
//request.Method="get";
HttpWebResponse response = (System.Net.HttpWebResponse)request.GetResponse();
Stream s = response.GetResponseStream();
//转化为XML,自己进行处理
XmlTextReader Reader = new XmlTextReader(s);
Reader.MoveToContent();
string strValue = Reader.ReadInnerXml();
Reader.Close();
strValue = strValue.Replace("<", "<");
strValue = strValue.Replace(">", ">");
return strValue;
}
(2)post 方式调用webservice 传参通过 parameters 字典 注意参数名要一直
public static string CallServiceByPost(string strURL,System.Collections.Specialized.StringDictionary parameters)
{
//string strURL = "http://localhost:12074/Service1.asmx/GetProductPrice";
//创建一个HTTP请求
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(strURL);
//Post请求方式
request.Method = "POST";
//内容类型
request.ContentType = "application/x-www-form-urlencoded";
//设置参数,并进行URL编码
StringBuilder codedString = new StringBuilder();
foreach (string key in parameters.Keys)
{
codedString.Append(HttpUtility.UrlEncode(key));
codedString.Append("=");
codedString.Append(HttpUtility.UrlEncode(parameters[key]));
codedString.Append("&");
}
string paraUrlCoded = codedString.Length == 0 ? string.Empty:codedString.ToString().Substring(0, codedString.Length - 1);
//string paraUrlCoded = HttpUtility.UrlEncode("ProductId");
//paraUrlCoded += "=" + HttpUtility.UrlEncode(this.textBox1.Text);
byte[] payload;
//将URL编码后的字符串转化为字节
payload = System.Text.Encoding.UTF8.GetBytes(paraUrlCoded);
//设置请求的ContentLength
request.ContentLength = payload.Length;
//发送请求,获得请求流
Stream writer = request.GetRequestStream();
//将请求参数写入流
writer.Write(payload, 0, payload.Length);
//关闭请求流
writer.Close();
//获得响应流
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream s = response.GetResponseStream();
//转化为XML,自己进行处理
XmlTextReader Reader = new XmlTextReader(s);
Reader.MoveToContent();
string strValue = Reader.ReadInnerXml();
Reader.Close();
strValue = strValue.Replace("<", "<");
strValue = strValue.Replace(">", ">");
return strValue;
}
}
js调用webservice
js 使用 post方式调用
<script type="text/javascript"> function RequestWebService() { //这是我们在第一步中创建的Web服务的地址 var URL = "http://localhost/YBWS/WebService.asmx"; //在这处我们拼接 var data; data = '<?xml version="1.0" encoding="utf-8"?>'; data = data + '<soap12:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap12="http://www.w3.org/2003/05/soap-envelope">'; data = data + '<soap12:Body>'; data = data + '<HelloWorld xmlns="http://tempuri.org/" />'; data = data + '</soap12:Body>'; data = data + '</soap12:Envelope>'; //创建异步对象 var xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); xmlhttp.Open("POST", URL, false); xmlhttp.SetRequestHeader("Content-Type", "application/soap+xml"); xmlhttp.Send(data); document.getElementById("data").innerHTML = xmlhttp.responseText; } </script>
ajax调用webservice
<script type="text/javascript">
//无参数调用
$(document).ready(function() {
$('#btn1').click(function() {
$.ajax({
type: "POST", //访问WebService使用Post方式请求
contentType: "application/json", //WebService 会返回Json类型
url: "WebService1.asmx/HelloWorld", //调用WebService的地址和方法名称组合 ---- WsURL/方法名
data: "{}", //这里是要传递的参数,格式为 data: "{paraName:paraValue}",下面将会看到
dataType: 'json',
success: function(result) { //回调函数,result,返回值
$('#dictionary').append(result.d);
}
});
});
});
//有参数调用
$(document).ready(function() {
$("#btn2").click(function() {
$.ajax({
type: "POST",
contentType: "application/json",
url: "WebService1.asmx/GetWish",
data: "{value1:'心想事成',value2:'万事如意',value3:'牛牛牛',value4:2009}",
dataType: 'json',
success: function(result) {
$('#dictionary').append(result.d);
}
});
});
});
//返回集合(引用自网络,很说明问题)
$(document).ready(function() {
$("#btn3").click(function() {
$.ajax({
type: "POST",
contentType: "application/json",
url: "WebService1.asmx/GetArray",
data: "{i:10}",
dataType: 'json',
success: function(result) {
$(result.d).each(function() {
//alert(this);
$('#dictionary').append(this.toString() + " ");
//alert(result.d.join(" | "));
});
}
});
});
});
//返回复合类型
$(document).ready(function() {
$('#btn4').click(function() {
$.ajax({
type: "POST",
contentType: "application/json",
url: "WebService1.asmx/GetClass",
data: "{}",
dataType: 'json',
success: function(result) {
$(result.d).each(function() {
//alert(this);
$('#dictionary').append(this['ID'] + " " + this['Value']);
//alert(result.d.join(" | "));
});
}
});
});
});
//返回DataSet(XML)
$(document).ready(function() {
$('#btn5').click(function() {
$.ajax({
type: "POST",
url: "WebService1.asmx/GetDataSet",
data: "{}",
dataType: 'xml', //返回的类型为XML ,和前面的Json,不一样了
success: function(result) {
//演示一下捕获
try {
$(result).find("Table1").each(function() {
$('#dictionary').append($(this).find("ID").text() + " " + $(this).find("Value").text());
});
}
catch (e) {
alert(e);
return;
}
},
error: function(result, status) { //如果没有上面的捕获出错会执行这里的回调函数
if (status == 'error') {
alert(status);
}
}
});
});
});
//Ajax 为用户提供反馈,利用ajaxStart和ajaxStop 方法,演示ajax跟踪相关事件的回调,他们两个方法可以添加给jQuery对象在Ajax前后回调
//但对与Ajax的监控,本身是全局性的
$(document).ready(function() {
$('#loading').ajaxStart(function() {
$(this).show();
}).ajaxStop(function() {
$(this).hide();
});
});
// 鼠标移入移出效果,多个元素的时候,可以使用“,”隔开
$(document).ready(function() {
$('div.button').hover(function() {
$(this).addClass('hover');
}, function() {
$(this).removeClass('hover');
});
});
</script>
简单方法:
返回复合类型
alert(result.d["StuName"]);
返回泛型集合
$(result.d).each(function(){
$("#result").append(this["Id"]+" "+this["StuName"]+"<br />");
});
dataset:
$(result).find("Table1").each(function() {
$('#result').append($(this).find("Id").text() + " " + $(this).find("Name").text()+"<br />");