我一直在进行一些谷歌搜索,但在这个主题上只取得了部分成功。我想知道是否有人可以建议使用 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/