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

轉載,侵刪:https://www.cnblogs.com/wgscd/p/10097402.html

發佈了15 篇原創文章 · 獲贊 0 · 訪問量 9664
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章