c# - 使用网络服务的 HTTP POST

标签 c# xml asmx

我一直在进行一些谷歌搜索,但在这个主题上只取得了部分成功。我想知道是否有人可以建议使用 C# 执行 HTTP POST 以将 XML 发送到 HTTP 服务的示例。

我有一个 asmx 网络服务,它从数据库中提取数据并将该数据保存到 XML 文档中。现在我必须使用 SOAP 协议(protocol)将该 XML 文档发送到 HTTP 服务。

我有这部分代码用于连接服务

WebRequest myReq = WebRequest.Create("https://WEB_URL");
 System.Net.ServicePointManager.CertificatePolicy = new CertificatePolicyClass();

                string username = "SOMETHING";
                string password = "ELSE";
                string usernamePassword = username + ":" + password;
                CredentialCache mycache = new CredentialCache();
                mycache.Add(new Uri("https://WEB_URL"), "Basic", new  NetworkCredential(username, password));
                myReq.Credentials = mycache;
                myReq.Headers.Add("Authorization", "Basic " + Convert.ToBase64String(new ASCIIEncoding().GetBytes(usernamePassword)));

                WebResponse wr = myReq.GetResponse();
                Stream receiveStream = wr.GetResponseStream();
                StreamReader reader = new StreamReader(receiveStream, Encoding.UTF8);
                string content = reader.ReadToEnd();

那么有没有人有将 XML 文档发送到 http 服务的代码,这部分我不知道怎么写,我不知道我是否在写跟踪上,我相信它必须像这样进行

request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";

所以请有人帮助我!谢谢!

最佳答案

这是我得到的,希望对你有用:

HttpWebRequest myReq = (HttpWebRequest)WebRequest.Create("https://WEB_URL");
myReq.Method = "POST";
myReq.ContentType = "text/xml";
myReq.Timeout = 30000;
myReq.Headers.Add("SOAPAction", ":\"#save\"");

byte[] PostData = Encoding.UTF8.GetBytes(xmlDocument);
myReq.ContentLength = PostData.Length;

using (Stream requestStream = myReq.GetRequestStream())
{
    requestStream.Write(PostData, 0, PostData.Length);
}

HttpWebResponse response = (HttpWebResponse)myReq.GetResponse();

关于c# - 使用网络服务的 HTTP POST,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11450836/

相关文章:

c# - 启动一个执行委托(delegate)的新进程

java - 将 XML 嵌入到 SOAP 请求的 CDATA 部分时出现解析错误

C#:显式命名空间未出现在生成的 XML 中

web-services - 使用 NHibernate 通过 Web 服务保存数据?

c# - Entity Framework 的连接字符串

c# - 如何使 Singleton 成为 Lazy 实例化类?

c# - 在 .NET 中设置 SSL 的正确方法

xml - src 解析 : Cannot resolve the name 'ds:Signature' to an 'element declaration' component

asp.net - ASMX技术完全过时了吗

c# - 将 .asmx Web 服务作为 Windows 服务运行