[C#] Summary of three ways to call webservice


Web Service, also known as web service, is a remote calling technology across programming languages ​​and operating system platforms. Web Service adopts standard SOAP protocol transmission (SOAP: Simple Object Access Protocol Simple Object Access Protocol, soap belongs to w3c standard. And soap protocol is an application layer protocol based on http to transmit xml data). Web Service uses WSDL as a description language, which is the instruction manual of Web Service. And W3C has formulated a set of transmission data types for Web Service, using xml to describe, that is, XSD (XML Schema Datatypes), the web Service interface written in any language must be converted into Web Service standard XSD when sending data.

[1] Add service references directly, and then call related methods.

[2] Use HttpPost request to call WebService

public class WebServiceDemo : System.Web.Services.WebService
    {
    
    

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

        [WebMethod]
        public string Sum(string param1, string param2)
        {
    
    
            int num1 = Convert.ToInt32(param1);
            int num2 = Convert.ToInt32(param2);

            int sum = num1 + num2;

            return sum.ToString();
        }
    }

Client calling code:

 class Program
    {
    
    
        static void Main(string[] args)
        {
    
    
            Program program = new Program();
            string url = "http://localhost:12544/WebServiceDemo.asmx";
            string method = "Sum";
            string num1 = "1";
            string num2 = "2";

            string result = program.HttpPostWebService(url, method, num1, num2);

            Console.WriteLine(result);
            Console.ReadKey();
        }

        public string HttpPostWebService(string url,string method,string num1,string num2)
        {
    
    
            string result = string.Empty;
            string param = string.Empty;
            byte[] bytes = null;
            Stream writer = null;
            HttpWebRequest request = null;
            HttpWebResponse response = null;

            param = HttpUtility.UrlEncode("x") + "=" + HttpUtility.UrlEncode(num1) + "&" + HttpUtility.UrlEncode("y") + "=" + HttpUtility.UrlEncode(num2);
            bytes = Encoding.UTF8.GetBytes(param);

            request = (HttpWebRequest)WebRequest.Create(url + "/" + method);
            request.Method = "POST";
            request.ContentType = "application/x-www-form-urlencoded";
            request.ContentLength = bytes.Length;

            try
            {
    
    
                writer = request.GetRequestStream();        //获取用于写入请求数据的Stream对象
            }
            catch (Exception ex)
            {
    
    
                return "";
            }

            writer.Write(bytes, 0, bytes.Length);       //把参数数据写入请求数据流
            writer.Close();

            try
            {
    
    
                response = (HttpWebResponse)request.GetResponse();      //获得响应
            }
            catch (WebException ex)
            {
    
    
                return "";
            }

            #region 这种方式读取到的是一个返回的结果字符串
            Stream stream = response.GetResponseStream();        //获取响应流
            XmlTextReader Reader = new XmlTextReader(stream);
            Reader.MoveToContent();
            result = Reader.ReadInnerXml();
            #endregion

            #region 这种方式读取到的是一个Xml格式的字符串
            //StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
            //result = reader.ReadToEnd();
            #endregion 

            response.Dispose();
            response.Close();

            //reader.Close();
            //reader.Dispose();

            Reader.Dispose();
            Reader.Close();

            stream.Dispose();
            stream.Close();

            return result;
        }
    }

Test with PostMan tool:
insert image description here

Note: The name of the method parameter variable in webservice is the same as the variable name you provided; param = HttpUtility.UrlEncode
("x") + "=" + HttpUtility.UrlEncode (num1) + "&" +
HttpUtility.UrlEncode ("y ") + "=" + HttpUtility.UrlEncode(num2);

[3] Dynamically call WebService

Dynamically call Webservice

If it's not for maintaining old projects, grpc has a look

GRPC is a high-performance, general-purpose open source RPC framework developed based on the underlying HTTP/2 protocol standard and the protocol layer Protobuf serialization protocol, and supports many development languages.

gRPC is also based on the idea of ​​defining a service and specifying its methods (including parameters and return types) that can be called remotely. Implement this interface on the server side and run a gRPC server to handle client calls. Having a stub on the client can act like a method on the server.

gRPC uses protocol buffers as the interface description language (IDL) and the underlying information exchange format

quote

Summary of three methods of C# calling webservice
Introduction to gRPC
WebService comprehensive explanation

Guess you like

Origin blog.csdn.net/weixin_44231544/article/details/124922474