zoukankan      html  css  js  c++  java
  • 【原创】C# HttpWebRequest 发送SOAP XML

    调用webservice的几种方法:

    方法一:添加web引用(简单/方便 局限客户端是.net)

    方法二:Post xml(本文重点讲述)

    方法三:使用微软MSXML2组件(好像在window server2008上就不支持)

    方法四:在页面上添加form post到服务端

    //创建HttpWebRequest 实例,使用WebRequest.Create
    HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create("服务地址");
    //发送请求
    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 += " <SoapHeader xmlns=\"http://www.52taiqiu.com/\">";
    soap += " <Login>" + txtUser.Text + "</Login>";
    soap += " <Password>" + txtPwd.Text + "</Password>";
    soap += " </SoapHeader>";
    soap += " </soap:Header>";

    soap += "<soap:Body>";

    soap += " <Request xmlns=\"http://www.52taiqiu.com/\">";
    soap += " <requestXml><![CDATA[" + txtRequest.Text + "]]></requestXml>";
    soap += " </Request>";
    soap += "</soap:Body>";
    soap += "</soap:Envelope>";

    webRequest.Headers["SoapAction"] = "http://www.52taiqiu.com/Request";

    //字符转字节
    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;
    }

  • 相关阅读:
    如何在 Microsoft Visual C# .NET 中实现 Microsoft Excel 自动化
    CentOS 6.5静态IP的设置(NAT和桥接都适用)
    myeclipse里如何添加mysql数据库
    Attribute value is quoted with " which must be escaped when used within the value 问题解决
    CentOS 6.5安装之后的网络配置
    Apache server for win解压版的安装与配置
    Oracle SQL 基本操作之 用户权限管理方法
    CentOS 6.5的安装详解
    IO类01
    可见性的问题
  • 原文地址:https://www.cnblogs.com/zhxhdean/p/2546277.html
Copyright © 2011-2022 走看看