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#方法调用一样。

原文地址:https://www.cnblogs.com/yuanshuang-club/p/15238341.html