c# HTTP Post代码没有得到预期的响应

本文关键字:响应 HTTP Post 代码 | 更新日期: 2023-09-27 18:12:48

我有一个示例htm文件具有以下结构,它post xml并获得响应xml。我需要用c#做同样的事情。请看我的c#代码下面的html.

<html>
<body>
<table>
<tr><td width=10%>&nbsp;</td><td><h2>API Test Form</h2></td></tr>
<tr><td width=10%>&nbsp;</td><td><h3>Command: get_Details </h3></td></tr>
<form action="https://test.test.com/getDetails" method=POST>

<tr>
<td width=10%>&nbsp;</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%>&nbsp;</td><td>&nbsp;</td></tr>
<tr><td width=10%>&nbsp;</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="。但这对回应没有影响。

c# HTTP Post代码没有得到预期的响应

发布XML时正确的内容类型是:

application/xml

text/xml内容类型已经过时了,而且严重损坏。

当您加载XML文档时,我认为您需要:

string postData = doc.OuterXml;

首先,我建议您使用Fiddler或类似的工具,以便您可以确切地看到在表单的POST请求中发送的内容,当您通过web浏览器单独执行它时。然后实例化HttpWebRequest对象,并按照您在Fiddler中看到的设置它的所有属性。

如问题中的html所述,请求xml被封装在TextArea控件

<textarea name="xml" rows=15 cols=80>

我用"xml="作为请求xml的前缀,这就成功了。