C#使用post发送和接收数据的方法
本文实例讲述了C#使用post发送和接收数据的方法。分享给大家供大家参考。具体实现方法如下:
publicpartialclassPost_Server:System.Web.UI.Page
{
protectedvoidPage_Load(objectsender,EventArgse)
{
stringtype="";
stringRe="";
Re+="数据传送方式:";
if(Request.RequestType.ToUpper()=="POST")
{
type="POST";
Re+=type+"<br/>参数分别是:<br/>";
SortedListtable=Param();
if(table!=null)
{
foreach(DictionaryEntryDeintable){
Re+="参数名:"+De.Key+"值:"+De.Value+"<br/>";
}
}
else
{Re="你没有传递任何参数过来!";}
}
else
{
type="GET";
Re+=type+"<br/>参数分别是:<br/>";
NameValueCollectionnvc=GETInput();
if(nvc.Count!=0)
{
for(inti=0;i<nvc.Count;i++){
Re+="参数名:"+nvc.GetKey(i)+"值:"+nvc.GetValues(i)[0]+"<br/>";
}
}
else
{Re="你没有传递任何参数过来!";}
}
Response.Write(Re);
}
//获取GET返回来的数据
privateNameValueCollectionGETInput()
{returnRequest.QueryString;}
//获取POST返回来的数据
privatestringPostInput()
{
try
{
System.IO.Streams=Request.InputStream;
intcount=0;
byte[]buffer=newbyte[1024];
StringBuilderbuilder=newStringBuilder();
while((count=s.Read(buffer,0,1024))>0)
{
builder.Append(Encoding.UTF8.GetString(buffer,0,count));
}
s.Flush();
s.Close();
s.Dispose();
returnbuilder.ToString();
}
catch(Exceptionex)
{throwex;}
}
privateSortedListParam()
{
stringPOSTStr=PostInput();
SortedListSortList=newSortedList();
intindex=POSTStr.IndexOf("&");
string[]Arr={};
if(index!=-1)//参数传递不只一项
{
Arr=POSTStr.Split('&');
for(inti=0;i<Arr.Length;i++)
{
intequalindex=Arr[i].IndexOf('=');
stringparamN=Arr[i].Substring(0,equalindex);
stringparamV=Arr[i].Substring(equalindex+1);
if(!SortList.ContainsKey(paramN))
//避免用户传递相同参数
{SortList.Add(paramN,paramV);}
else//如果有相同的,一直删除取最后一个值为准
{
SortList.Remove(paramN);SortList.Add(paramN,paramV);
}
}
}
else//参数少于或等于1项
{
intequalindex=POSTStr.IndexOf('=');
if(equalindex!=-1)
{//参数是1项
stringparamN=POSTStr.Substring(0,equalindex);
stringparamV=POSTStr.Substring(equalindex+1);
SortList.Add(paramN,paramV);
}
else//没有传递参数过来
{SortList=null;}
}
returnSortList;
}
}
protectedvoidButton1_Click(objectsender,EventArgse)
{
Encodingencode=System.Text.Encoding.GetEncoding("utf-8");
byte[]arrB=encode.GetBytes("aa=aa&bb=好飞");
HttpWebRequestmyReq=(HttpWebRequest)WebRequest.Create("http://localhost:11626/MyTest/Post_Server.aspx");
myReq.Method="POST";
myReq.ContentType="application/x-www-form-urlencoded";
myReq.ContentLength=arrB.Length;
StreamoutStream=myReq.GetRequestStream();
outStream.Write(arrB,0,arrB.Length);
outStream.Close();
//接收HTTP做出的响应
WebResponsemyResp=myReq.GetResponse();
StreamReceiveStream=myResp.GetResponseStream();
StreamReaderreadStream=newStreamReader(ReceiveStream,encode);
Char[]read=newChar[256];
intcount=readStream.Read(read,0,256);
stringstr=null;
while(count>0)
{
str+=newString(read,0,count);
count=readStream.Read(read,0,256);
}
readStream.Close();
myResp.Close();
Response.Write(str);
}
希望本文所述对大家的C#程序设计有所帮助。