httpclient连接webservice

1. 创建webservice服务

  1. 新建asp.net项目,选择.net framework 4.7.2
    在这里插入图片描述
  2. 新建webservice服务
    在这里插入图片描述
  3. 修改代码
using System.Web.Services;
using System.Web.Services.Protocols;

namespace WebService01
{
    /// <summary>
    /// WebService1 的摘要说明
    /// </summary>
    [WebService(Namespace = "http://www.wujialiang.com/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    // 若要允许使用 ASP.NET AJAX 从脚本中调用此 Web 服务,请取消注释以下行。 
    // [System.Web.Script.Services.ScriptService]
    public class WebService1 : System.Web.Services.WebService
    {
        /// <summary>
        /// 简单测试
        /// </summary>
        /// <returns></returns>
        [WebMethod(Description ="HelloWord接口")]
        public string HelloWorld()
        {
            return "Hello World";
        }

        /// <summary>
        /// 复杂类型
        /// </summary>
        /// <param name="a"></param>
        /// <param name="b"></param>
        /// <returns></returns>
        [WebMethod(Description ="加法计算")]
        public ResultModel Add(int a, int b)
        {
            var c = a + b;
            return new ResultModel()
            {
                Success = true,
                Result = c
            };
        }

        //声明Soap头实例
        public MySoapHeader diyHeader = new MySoapHeader();

        /// <summary>
        /// 授权验证
        /// </summary>
        /// <returns></returns>
        [System.Web.Services.Protocols.SoapHeader("diyHeader")]
        [WebMethod(Description ="授权验证的数据")]
        public string GetAuthData()
        {
            if (diyHeader.UserName == "wjl" && diyHeader.PassWord == "wujialiang")
                return "通过授权";
            else
                return "未通过授权";
        }
    }

    public class ResultModel
    {
        public bool Success { get; set; }
        public int Result { get; set; }
    }

    /// <summary>
    /// 自定义SoapHeader
    /// </summary>
    public class MySoapHeader : SoapHeader
    {
        private string userName = string.Empty;
        private string passWord = string.Empty;

        /// <summary>
        /// 构造函数
        /// </summary>
        public MySoapHeader()
        {
        }

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="userName">用户名</param>
        /// <param name="passWord">密码</param>
        public MySoapHeader(string userName, string passWord)
        {
            this.userName = userName;
            this.passWord = passWord;
        }

        /// <summary>
        /// 获取或设置用户用户名
        /// </summary>
        public string UserName
        {
            get { return userName; }
            set { userName = value; }
        }

        /// <summary>
        /// 获取或设置用户密码
        /// </summary>
        public string PassWord
        {
            get { return passWord; }
            set { passWord = value; }
        }
    }
}
  1. 启动webservice查看效果
    在这里插入图片描述
    在这里插入图片描述
    在这里插入图片描述
    在这里插入图片描述

2. httpclient调用

  1. 创建控制台应用程序
  2. 编写代码
using System;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Xml;

namespace WebServiceUse01
{
    public class Program
    {
        static string url = "http://localhost:59523/WebService1.asmx";

        static void Main(string[] args)
        {
            HelloWordTest().Wait();
            Console.WriteLine("HelloWordTest执行完毕....");
            AddTest().Wait();
            Console.WriteLine("AddTest执行完毕....");
            GetAuthDataTest().Wait();
            Console.WriteLine("GetAuthDataTest执行完毕....");
            GetAuthDataFailTest().Wait();
            Console.WriteLine("GetAuthDataFailTest执行完毕...");
            Console.ReadKey();
        }

        /// <summary>
        /// 测试helloWord接口
        /// </summary>
        static async Task HelloWordTest()
        {
            HttpClient httpClient = new HttpClient();
            httpClient.DefaultRequestHeaders.Add("SOAPAction", "http://www.wujialiang.com/HelloWorld");
            StringBuilder body = new StringBuilder();
            body.Append("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
            body.Append("<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/\">");
            body.Append("<soap:Body>");
            body.Append("<HelloWorld xmlns=\"http://www.wujialiang.com/\" />");
            body.Append("</soap:Body>");
            body.Append("</soap:Envelope>");
            StringContent content = new StringContent(body.ToString(), Encoding.UTF8, "text/xml");
            var response = await httpClient.PostAsync(url, content);
            if (response.StatusCode != HttpStatusCode.OK)
            {
                Console.WriteLine("获取数据失败");
                return;
            }
            var resultXml = await response.Content.ReadAsStringAsync();
            XmlDocument doc = new XmlDocument();
            doc.LoadXml(resultXml);
            var result = doc.GetElementsByTagName("soap:Envelope");
            Console.WriteLine(result.Count);
            if (result.Count > 0)
            {
                Console.WriteLine(result[0].InnerText);
            }
        }

        /// <summary>
        /// 测试加法
        /// </summary>
        /// <returns></returns>
        static async Task AddTest()
        {
            HttpClient httpClient = new HttpClient();
            httpClient.DefaultRequestHeaders.Add("SOAPAction", "http://www.wujialiang.com/Add");
            StringBuilder body = new StringBuilder();
            body.Append("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
            body.Append("<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/\">");
            body.Append("<soap:Body>");
            body.Append("<Add xmlns=\"http://www.wujialiang.com/\">");
            body.Append("<a>1</a>");
            body.Append("<b>2</b>");
            body.Append("</Add>");
            body.Append("</soap:Body>");
            body.Append("</soap:Envelope>");
            StringContent content = new StringContent(body.ToString(), Encoding.UTF8, "text/xml");
            var response = await httpClient.PostAsync(url, content);
            if (response.StatusCode != HttpStatusCode.OK)
            {
                Console.WriteLine("获取数据失败");
                return;
            }
            var resultXml = await response.Content.ReadAsStringAsync();
            XmlDocument doc = new XmlDocument();
            doc.LoadXml(resultXml);
            var result = doc.GetElementsByTagName("soap:Envelope");
            Console.WriteLine(result.Count);
            if (result.Count > 0)
            {
                Console.WriteLine(result[0].InnerText);
                Console.WriteLine(result[0].InnerXml);
            }
        }

        /// <summary>
        /// 认证数据测试
        /// </summary>
        /// <returns></returns>
        static async Task GetAuthDataTest()
        {
            HttpClient httpClient = new HttpClient();
            httpClient.DefaultRequestHeaders.Add("SOAPAction", "http://www.wujialiang.com/GetAuthData");
            StringBuilder body = new StringBuilder();
            body.Append("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
            body.Append("<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/\">");
            
            body.Append("<soap:Header>");
            body.Append("<MySoapHeader xmlns=\"http://www.wujialiang.com/\">");
            body.Append("<UserName>wjl</UserName>");
            body.Append("<PassWord>wujialiang</PassWord>");
            body.Append("</MySoapHeader>");
            body.Append("</soap:Header>");

            body.Append("<soap:Body>");
            body.Append("<GetAuthData xmlns=\"http://www.wujialiang.com/\" />");
            body.Append("</soap:Body>");
            body.Append("</soap:Envelope>");
            StringContent content = new StringContent(body.ToString(), Encoding.UTF8, "text/xml");
            var response = await httpClient.PostAsync(url, content);
            if (response.StatusCode != HttpStatusCode.OK)
            {
                Console.WriteLine("获取数据失败");
                return;
            }
            var resultXml = await response.Content.ReadAsStringAsync();
            XmlDocument doc = new XmlDocument();
            doc.LoadXml(resultXml);
            var result = doc.GetElementsByTagName("soap:Envelope");
            Console.WriteLine(result.Count);
            if (result.Count > 0)
            {
                Console.WriteLine(result[0].InnerText);
                Console.WriteLine(result[0].InnerXml);
            }
        }

        /// <summary>
        /// 认证数据测试
        /// </summary>
        /// <returns></returns>
        static async Task GetAuthDataFailTest()
        {
            HttpClient httpClient = new HttpClient();
            httpClient.DefaultRequestHeaders.Add("SOAPAction", "http://www.wujialiang.com/GetAuthData");
            StringBuilder body = new StringBuilder();
            body.Append("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
            body.Append("<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/\">");

            body.Append("<soap:Header>");
            body.Append("<MySoapHeader xmlns=\"http://www.wujialiang.com/\">");
            body.Append("<UserName>wjl</UserName>");
            body.Append("<PassWord>wujidddaliang</PassWord>");
            body.Append("</MySoapHeader>");
            body.Append("</soap:Header>");

            body.Append("<soap:Body>");
            body.Append("<GetAuthData xmlns=\"http://www.wujialiang.com/\" />");
            body.Append("</soap:Body>");
            body.Append("</soap:Envelope>");
            StringContent content = new StringContent(body.ToString(), Encoding.UTF8, "text/xml");
            var response = await httpClient.PostAsync(url, content);
            if (response.StatusCode != HttpStatusCode.OK)
            {
                Console.WriteLine("获取数据失败");
                return;
            }
            var resultXml = await response.Content.ReadAsStringAsync();
            XmlDocument doc = new XmlDocument();
            doc.LoadXml(resultXml);
            var result = doc.GetElementsByTagName("soap:Envelope");
            Console.WriteLine(result.Count);
            if (result.Count > 0)
            {
                Console.WriteLine(result[0].InnerText);
                Console.WriteLine(result[0].InnerXml);
            }
        }
    }
}

  1. 测试
    在这里插入图片描述

备注也可以通过webRequest实现

原理一样,代码稍微不同

var url = $"{options.Value.SSOUrl}/TokenService.asmx";
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url);
 //发送请求
 webRequest.Method = "POST";
 //编码
 webRequest.ContentType = "text/xml";
 webRequest.Headers["SOAPAction"] = "http://passport.alaibao.cn/IfExistsGetUid";
 //字符转字节
 byte[] bytes = Encoding.UTF8.GetBytes(body.ToString());
 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();
 }
 catch (Exception ex)
 {

 }
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

假装我不帅

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值