使用HTTP-GET方式訪問
HTTP-GET方式訪問#region HTTP-GET方式訪問
private void button1_Click(Object sender,System.EventArgs e)
{
System.Net.HttpWebRequest Req;
string strGet="http://localhost/HelloWord?name=";
strGet=strGet+textBox1.Text;
Rep=(System.net.HttpWebRequest)WebRequest.Create(strGet);
System.Net.HttpWebResponse response;
response=(System.net.HttpWebResponse).Req.GetResponse();
System.IO.Stream s;
s=response.GetResponseStream();
XmlTextReader Reader=new XmlTextReader(s);
Reader.MoveToContent();
label1.Text=Reader.ReaderInnerXml();
Reader.Close();
}
#endregion
使用HTTP-POST方式訪問
HTTP-POST方式訪問#region HTTP-POST方式訪問
private void button1_Click(Object sender,System.EventArgs e)
{
string url;
url="http://localhost/HelloWord";
HttpWebRequest Req;
Req=(HttpWebRequest)WebRequest.Create(url);
//POST方式請求
Rep.Method="POST";
//內容類型
Rep.ContentType="application/x-www-form-urlencoded";
//參數經過URL編碼
string paraUrlCoded=System.Web.HttpUtility.UrlEncode("name");
paraUrlCoded=paraUrlCoded+"="+System.Web.HttpUtility.UrlEncode(textBox1.Text);
byte[] payload;
//將URL編碼後的字串轉化為位元組
payload=System.TextEncoding.UTF8.GetBytes(paraUrlCoded);
//佈建要求的ContentLength
Req.ContentLength=payload.Length;
//獲得請求流
Stream writer=Req.GetRequestStream();
//將請求參數寫入流
writer.Write(payload,0,payload.Length);
//關閉請求流
writer.Close();
//獲得響應流
HttpWebResponse response=(HttpWebResponse)Req.GetResponse();
System.IO.Stream s;
s=response.GetResponseStream();
XmlTextReader Reader=new XmlTextReader(s);
Reader.MoveToContent();
label1.Text=Reader.ReaderInnerXml();
Reader.Close();
}
#endregion
使用SOAP方式訪問
首先客戶代理用XmlSerializer對象進行參數序列化為XML.伺服器端相應的
XmlSerializer對象還原序列化,從而從XML中擷取調用參數.
如下:Person類
Person類#region Person類
public class Person
{
private String name;
private int age;
public String Name;
{
get
{
return name;
}
set
{
name=value;
}
}
public int Age
{
get
{
return age;
}
set
{
age=value;
}
}
public void Show()
{
Console.WriteLine("Name"={0},Age={1},Name,Age);
}
}
#endregionSOAP方式訪問#region SOAP方式訪問
static void Main(String[] args)
{
//執行個體化XML序列器
XmlSerializer serializer=net XmlSerializer(typeof(Person));
//產生序列化對象
Person p=new Person();
p.Age=22;
p.Name="Jack.Xiao";
//產生記憶體流
MemoryStream s=new MemoryStream();
//書寫器
StreamWriter writer=new StreamWriter(s,Encoding.UTF8);
serializer.Serialize(writer,p);
//定位到流的頭
s.Seek(0,SeekOrigin.Begin);
StreamReader reader=new StreamReader(s,Encoding.UTF8);
Person p2=(Person)serializer.Deserialize(reader);
p2.Show();
Console.WriteLine("==========XML內容如下===============");
//顯示XML內容
s.Seek(0,SeekOrigin.Begin);
String xmls=reader.ReadLine()
while(xmls!=null)
{
Console.WriteLine(xmls);
xmls=reader.ReadLine();
}
//關閉流
reader.Close();
}
#endregion