我在下面的curl请求中想要转换为C#代码。我只是不确定HttpWebRequest中的“ -data-binary ”是什么。
curl -s -H "Content-Type:application/xml" -X POST --data-binary @C:\path\to\file.xml "https://somerestURL?create"
到目前为止,以下是我的代码:
var xmlFile = "C:\\path\\to\\file.xml";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
NetworkCredential cred = new NetworkCredential(uname, cipher);
CredentialCache cache = new CredentialCache { { url, "Basic", cred } };
request.PreAuthenticate = true;
request.Credentials = cache;
request.Method = "POST";
request.ContentType = "application/xml";
如果您需要更多信息,我可以提供信息。谢谢。
答案 0 :(得分:1)
我专注于搜索curl到c#代码的转换/等效性,但是我没有走运。 因此,我研究了XML POSTING,下面是我的工作代码。
// initiate xml
XmlDocument xml = new XmlDocument();
xml.Load(xmlFile);
byte[] bytes = Encoding.ASCII.GetBytes(xml.InnerXml);
// setup request
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
NetworkCredential cred = new NetworkCredential(uname, cipher);
CredentialCache cache = new CredentialCache { { url, "Basic", cred } };
request.PreAuthenticate = true;
request.Credentials = cache;
request.Method = "POST";
request.ContentType = "application/xml; encoding='utf-8'";
request.ContentLength = bytes.Length;
// stream
Stream requestStream = request.GetRequestStream();
requestStream.Write(bytes, 0, bytes.Length);
requestStream.Close();
// response
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream responseStream = response.GetResponseStream();
StreamReader readStream = new StreamReader(responseStream, Encoding.Default);
var xmlResponse = readStream.ReadToEnd();
我从这篇文章中得到了自己的想法,并根据自己的要求做了一些改动: HTTP post XML data in C#