C#后台HttpWebRequest代碼調用WebService


一、創建一個webservices服務

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;

namespace WeServices
{
    /// <summary>
    /// MyWebService 的摘要說明
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    // 若要允許使用 ASP.NET AJAX 從腳本中調用此 Web 服務,請取消注釋以下行。 
    // [System.Web.Script.Services.ScriptService]
    public class MyWebService : System.Web.Services.WebService
    {

        [WebMethod]
        public string HelloWorld()
        {
            return "Hello World";
        }

        [WebMethod]
        public int Add(int a, int b)
        {
            return a + b;
        }
    }
}

 

 點擊運行然后瀏覽器輸入地址:

 

 然后點擊Add方法 我們就能查看到當前webservice調用時需要的參數

 

 二、根據上面的調用分析我們可以在代碼中進行調用

using System;
using System.Collections;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Xml;

namespace WebTest
{
    class Program
    {
        static void Main(string[] args)
        {
            string url = "http://localhost:5898/MyWebService.asmx";
            string par = "<?xml version=\"1.0\" encoding=\"utf-8\"?>"+
                            "<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:Body>"+
                                "<Add xmlns=\"http://tempuri.org/\">"+
                                  "<a>10</a>"+
                                  "<b>20</b>"+
                                "</Add>"+
                              "</soap:Body>"+
                            "</soap:Envelope>";
            string result = GetService(url, par);
            Console.WriteLine(result);
            Console.ReadKey();
        }

        public static string Get(string url, string par)
        {
            string res = "";
            HttpClient client = new HttpClient();
            HttpContent httpContent = new StringContent(par);
            httpContent.Headers.ContentType.Parameters.Add(new System.Net.Http.Headers.NameValueHeaderValue("Content-Type","text/xml; charset=utf-8"));
            res = client.PostAsync(url, httpContent).Result.Content.ReadAsStringAsync().Result;
            return res;
        }

        public static string GetService(string url, string par)
        {
            string res = "";
            HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url);
            HttpWebResponse webResponse = null;
            Stream writer = null;
            Stream reader = null;
            byte[] data = Encoding.UTF8.GetBytes(par);
            webRequest.Method = "POST";
            webRequest.ContentType = "text/xml; charset=utf-8";
            webRequest.ContentLength = data.Length;

            //寫入參數
            try
            {
                writer = webRequest.GetRequestStream();
            }
            catch (Exception ex)
            {
                throw ex;
            }
            writer.Write(data, 0, data.Length);
            writer.Close();

            //獲取響應
            try
            {
                webResponse = (HttpWebResponse)webRequest.GetResponse();
            }
            catch (Exception ex)
            {
                throw ex;
            }
            reader = webResponse.GetResponseStream();
            StreamReader streamReader = new StreamReader(reader, Encoding.UTF8);
            res = streamReader.ReadToEnd();
            reader.Close();
            streamReader.Close();
            XmlDocument document = new XmlDocument();
            document.LoadXml(res);
            res = document.GetElementsByTagName("AddResult").Item(0).InnerText;
            return res;
        }
    }
}

這樣就能直接獲取到接口返回的值了,webservice接口調用還是很簡單的,瀏覽器中給出的調用文檔很詳細,根據文檔我們就能很順利的進行代碼調用。

當然我們也能在項目中直接引入該服務,獲取該webservice的wsdl文件然后引入到項目中,直接實例化服務對象,像方法一樣進行調用,這里我就不演示此種方法了,就和引入一個動態庫一樣 只不過這里是引用服務而已,其他的使用和C#方法調用一樣。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM