• C# httpRequest Soap请求


    一般添加web服务引用是.NET用代理类模式 创建SOAP请求代理类,代理类是.NET开发工具VS自动给你生成。

    下面用一般HTTP的模式有时候可能更合适,原理是构造SOAP请求的XML后POST过去:

    下面是HelloWorld的例子

    private void button1_Click(object sender, EventArgs e)
            {
    
                //创建HttpWebRequest 实例,使用WebRequest.Create
                HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create("http://localhost:1198/WebSite1/Service.asmx");
                //发送请求
                webRequest.Method = "POST";
                //编码
                webRequest.ContentType = "text/xml";
                string soap = "<?xml version="1.0" encoding="utf-8"?>";
                soap += "<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">";
                soap += " <soap:Header>";
                soap += " </soap:Header>";
                soap += "<soap:Body>";
                soap += "  <HelloWorld xmlns="http://tempuri.org/" />";
                soap += "</soap:Body>";
                soap += "</soap:Envelope>";
              // webRequest.Headers["SoapAction"] = "http://localhost:1198/WebSite1/Service.asmx";
    
                //字符转字节
                byte[] bytes = Encoding.UTF8.GetBytes(soap);
                Stream writer = webRequest.GetRequestStream();
                writer.Write(bytes, 0, bytes.Length);
                writer.Flush();
                writer.Close();
                string result = "";
                //返回 HttpWebResponse
                try
                {
                    HttpWebResponse hwRes = webRequest.GetResponse() as HttpWebResponse;
                    if (hwRes.StatusCode == System.Net.HttpStatusCode.OK)
                    {//是否返回成功
                        Stream rStream = hwRes.GetResponseStream();
                        //流读取
                        StreamReader sr = new StreamReader(rStream, Encoding.UTF8);
                        result = sr.ReadToEnd();
                        sr.Close();
                        rStream.Close();
                    }
                    else
                    {
                        result = "连接错误";
                    }
                    //关闭
                    hwRes.Close();
                    txtResponse.Text = result;
                }
                catch (System.Net.WebException ex)
                {
                    String responseFromServer = ex.Message.ToString() + " ";
                    if (ex.Response != null)
                    {
                        using (WebResponse response = ex.Response)
                        {
                            Stream data = response.GetResponseStream();
                            using (StreamReader reader = new StreamReader(data))
                            {
                                responseFromServer += reader.ReadToEnd();
                            }
                        }
                    }
                    txtResponse.Text = responseFromServer;
                }
    
    
            }
    

      

    不错意外会返回如下:

    <?xml version="1.0" encoding="utf-8"?><soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"><soap:Body><HelloWorldResponse xmlns="http://tempuri.org/"><HelloWorldResult>Hello World</HelloWorldResult></HelloWorldResponse></soap:Body></soap:Envelope>
    

      

     不构造XML结构请求也是可以的:

    /*
                 /*POST /WebSite1/Service.asmx/HelloWorld HTTP/1.1
    Host: localhost
    Content-Type: application/x-www-form-urlencoded
    Content-Length: length
                 */
                //创建HttpWebRequest 实例,使用WebRequest.Create
                HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create("http://localhost:1198/WebSite1/Service.asmx/HelloWorld");
                //发送请求
                webRequest.Method = "POST";
                webRequest.ContentType = "application/x-www-form-urlencoded";
                webRequest.ContentLength=0;
                string soap = "";//请求参数如 soap = "str=wgscd&num=123";
                //字符转字节
                byte[] bytes = Encoding.UTF8.GetBytes(soap);
                Stream writer = webRequest.GetRequestStream();
                writer.Write(bytes, 0, bytes.Length);
                writer.Flush();
                writer.Close();
                string result = "";
                //返回 HttpWebResponse
                try
                {
                    HttpWebResponse hwRes = webRequest.GetResponse() as HttpWebResponse;
                    if (hwRes.StatusCode == System.Net.HttpStatusCode.OK)
                    {//是否返回成功
                        Stream rStream = hwRes.GetResponseStream();
                        //流读取
                        StreamReader sr = new StreamReader(rStream, Encoding.UTF8);
                        result = sr.ReadToEnd();
                        sr.Close();
                        rStream.Close();
                    }
                    else
                    {
                        result = "连接错误";
                    }
                    //关闭
                    hwRes.Close();
                    txtResponse.Text = result;
                }
                catch (Exception ex)
                {
                    txtResponse.Text = ex.Message ;
                   
                }
    

      

    会返回:

    <?xml version="1.0" encoding="utf-8"?>
    <string xmlns="http://tempuri.org/">Hello World</string>
    

      

     不构造XML请求结构的一个死穴是,那种传人参数是某个对象/类的情况就GG了。

    如:

    [WebMethod]
    public DataRet HelloWorld(DataRequest dt)
    {

    DataRet d =new DataRet();
    return d;
    }

  • 相关阅读:
    【JAVA反射】自定义类加载器
    工厂模式+反射+泛型
    wsdl文件生成webservice代理类及使用生成的代理类
    WebApi 做接口遇到的问题总结
    region URL请求数据
    LinQ 创建连接、简单增删改查
    JS整理
    WebForm 全局对象、commend
    WebForm 内置对象、数据增删改、状态保持
    WebForm 控件(二)
  • 原文地址:https://www.cnblogs.com/wgscd/p/10097402.html
Copyright © 2020-2023  润新知