代码改变世界

c# WebRequest post get 调用 WebSerivce

2017-12-01 12:21  多多多多多奈特  阅读(184)  评论(0)    收藏  举报

Get

public void GetFunction()
        {
            string url = @"http://localhost:50018/WebService1.asmx/HelloWorld2?name=sssspppppp";
            WebRequest request = WebRequest.Create(url);

            byte[] byteArray = Encoding.UTF8.GetBytes("");

            request.Method = "GET";
            request.ContentType = "application/x-www-form-urlencoded";
            request.ContentLength = byteArray.Length;

            WebResponse response = request.GetResponse();

            //读取返回
            Stream s = response.GetResponseStream();
            //服务器端返回的是一个XML格式的字符串,XML的Content才是我们所需要的Json数据
            XmlTextReader reader = new XmlTextReader(s);
            reader.MoveToContent();
            string strValue = reader.ReadInnerXml();//取出Content中的Json数据 

            s.Close();
            reader.Close();
            response.Close();
        }
View Code

 

Post

  public void PostFunction()
        {
            string url = @"http://localhost:50018/WebService1.asmx/HelloWorld";
            WebRequest request = WebRequest.Create(url);

            byte[] byteArray = Encoding.UTF8.GetBytes("name=sssspppppp");

            request.Method = "POST";
            request.ContentType = "application/x-www-form-urlencoded";
            request.ContentLength = byteArray.Length;

            //写参数
            Stream dataStream = request.GetRequestStream();
            dataStream.Write(byteArray, 0, byteArray.Length);
            dataStream.Close();

            WebResponse response = request.GetResponse();

            //读取返回
            Stream s = response.GetResponseStream();
            //服务器端返回的是一个XML格式的字符串,XML的Content才是我们所需要的Json数据
            XmlTextReader reader = new XmlTextReader(s);
            reader.MoveToContent();
            string strValue = reader.ReadInnerXml();//取出Content中的Json数据 

            s.Close();
            reader.Close();
            dataStream.Close();
            response.Close();
        }
View Code

 

配置文件加入

 <webServices>
        <protocols>
          <add name="HttpGet"/>
          <add name="HttpPost"/>
        </protocols>
      </webServices>
View Code