欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

C#发送HttpPost请求来调用WebService的方法

程序员文章站 2023-12-03 09:26:10
复制代码 代码如下:void updatecontactsign()        { &n...

复制代码 代码如下:

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;
        }