我有一个带有以下结构的示例htm文件,它对xml进行POST并获取响应xml。我需要用C#做同样的事情。请参阅html下方的C#代码。
<html>
<body>
<table>
<tr><td width=10%> </td><td><h2>API Test Form</h2></td></tr>
<tr><td width=10%> </td><td><h3>Command: get_Details </h3></td></tr>
<form action="https://test.test.com/getDetails" method=POST>
<tr>
<td width=10%> </td>
<td>
<textarea name="xml" rows=15 cols=80>
<?xml version="1.0" encoding="UTF-8"?>
<Request>
<test1>xcvb</test1>
</Request>
</textarea>
</td>
</tr>
<tr><td width=10%> </td><td> </td></tr>
<tr><td width=10%> </td><td><input type="submit" value="Submit Request"></td></tr>
</table>
</form>
</body>
</html>
private static string MSDNHttpPost1()
{
// Create a request using a URL that can receive a post.
WebRequest request = WebRequest.Create("https://test.test.com/getDetails");
// Set the Method property of the request to POST.
request.Method = "POST";
// Create POST data and convert it to a byte array.
var doc = new XmlDocument();
doc.Load(@"C:\request.xml");
string postData = doc.InnerXml;
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
// Set the ContentType property of the WebRequest.
request.ContentType = "application/x-www-form-urlencoded";
//request.ContentType = "text/xml";
// Set the ContentLength property of the WebRequest.
//request.ContentLength = byteArray.Length;
// Get the request stream.
Stream dataStream = request.GetRequestStream();
// Write the data to the request stream.
dataStream.Write(byteArray, 0, byteArray.Length);
// Close the Stream object.
dataStream.Close();
// Get the response.
WebResponse response = request.GetResponse();
// Display the status.
Console.WriteLine(((HttpWebResponse)response).StatusDescription);
// Get the stream containing content returned by the server.
dataStream = response.GetResponseStream();
// Open the stream using a StreamReader for easy access.
StreamReader reader = new StreamReader(dataStream);
// Read the content.
string responseFromServer = reader.ReadToEnd();
// Display the content.
Console.WriteLine(responseFromServer);
// Clean up the streams.
reader.Close();
dataStream.Close();
response.Close();
return responseFromServer;
}
C#代码改编自MSDN网站。但响应显示一条错误消息,基本上说服务器无法读取xml文件。我被建议在发布时在xml之前包含“data =”。但这对回应没有影响。
关于我缺少什么的任何线索?。
答案 0 :(得分:1)
答案 1 :(得分:0)
首先,我建议您使用Fiddler或类似工具,这样您就可以通过Web浏览器单独执行单独执行表单的POST请求时查看正在发送的内容。然后实例化HttpWebRequest
对象,并按照你在Fiddler中看到的那样设置它的所有属性。
答案 2 :(得分:0)
当你加载XML文档时,我想你想要:
string postData = doc.OuterXml;
答案 3 :(得分:0)
如问题中的html所述,请求xml位于TextArea控件中
<textarea name="xml" rows=15 cols=80>
我将请求xml的前缀加上“xml =”,这就是诀窍。