C#发送HttpPost请求来调用WebService的方法
void updatecontactsign()
{
string serverpage ="http://localhost/webservice/myservice.asmx";
try
{
//serverpage += "?op=tangramaction";
serverpage += "/myaction";//myaction是webservice中的方法
string strxml="<a objid=\"9\"></a>",;//第一个参数
string strdata="contactsign|990011|我的数据";//第二个参数
string res = httpconnecttoserver(serverpage, strxml, strdata);
//messagebox.show(res);
}
catch (exception ex)
{
}
}
//发送消息到服务器
public string httpconnecttoserver(string serverpage,string strxml,string strdata)
{
string postdata = "strxml=" + strxml+"&strdata="+strdata;
byte[] dataarray = encoding.default.getbytes(postdata);
//创建请求
httpwebrequest request = (httpwebrequest)httpwebrequest.create(serverpage);
request.method = "post";
request.contentlength = dataarray.length;
request.contenttype = "application/x-www-form-urlencoded";
//创建输入流
stream datastream = null;
try
{
datastream = request.getrequeststream();
}
catch (exception)
{
return null;//连接服务器失败
}
//发送请求
datastream.write(dataarray, 0, dataarray.length);
datastream.close();
//读取返回消息
string res = string.empty;
try
{
httpwebresponse response = (httpwebresponse)request.getresponse();
streamreader reader = new streamreader(response.getresponsestream(), encoding.utf8);
res = reader.readtoend();
reader.close();
}
catch (exception ex)
{
return null;//连接服务器失败
}
return res;
}