C# 中的 HTTP 发布 XML 数据

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17535872/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 09:46:55  来源:igfitidea点击:

HTTP post XML data in C#

c#xmlhttp-headers

提问by Alma

I need to HTTP post XML data to a URL that has Textarea with the name of XMLdata. My XMl data is ready and is inside of XDocument Sendingxml = xml; but the post code that I have tried is not working. Mostly because I don't know how to put the XML data in postData Variable as it only accept string. This is my code:

我需要将 XML 数据通过 HTTP 发送到一个 URL,该 URL 具有名称为 XMLdata 的 Textarea。我的 XMl 数据已准备就绪,位于 XDocument Sendingxml = xml; 中。但是我尝试过的邮政编码不起作用。主要是因为我不知道如何将 XML 数据放入 postData 变量中,因为它只接受字符串。这是我的代码:

        XDocument Sendingxml = xml;

        //  string Sendingxml = "<?xml version=1.0 encoding=UTF-8> <PluginData> <Credential UserName=avosfieldagent01 AuthenticationToken=61cc3957744742dca238c4dd7cbca702 /><Session><PropertyAddress>5 Crosskey</PropertyAddress><PropertyAddress2/><PropertyCity>California</PropertyCity><PropertyState>CA</PropertyState><PropertyZip>92620</PropertyZip><PropertyType>Condo</PropertyType><SourceReferenceId>45643</SourceReferenceId><SessionId>2013070100158346</SessionId><SessionCompleteReturnURL/><CustomerId/><BluebookOrderCheckSum>681a598cf23f412095f6092c281823e6</BluebookOrderCheckSum><BluebookOrderId>11160</BluebookOrderId> </Session></PluginData>";

        // Create a request using a URL that can receive a post. 
        WebRequest request =
            WebRequest.Create("https://test.bluebookcva.net/order/testdirectplugin/3");
        // Set the Method property of the request to POST.
        request.Method = "POST";

        // Create POST data and convert it to a byte array.
        string postData = "XMLData=" + Sendingxml;    //My problem is here as I need postData  as XDocument.


        byte[] byteArray = Encoding.UTF8.GetBytes(postData);
        // Set the ContentType property of the WebRequest.
        request.ContentType = "application/x-www-form-urlencoded";
        // 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();

采纳答案by AlliterativeAlice

In General:

一般来说:

An example of an easy way to post XML data and get the response (as a string) would be the following function:

发布 XML 数据并获取响应(作为字符串)的简单方法的示例是以下函数:

public string postXMLData(string destinationUrl, string requestXml)
{
    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(destinationUrl);
    byte[] bytes;
    bytes = System.Text.Encoding.ASCII.GetBytes(requestXml);
    request.ContentType = "text/xml; encoding='utf-8'";
    request.ContentLength = bytes.Length;
    request.Method = "POST";
    Stream requestStream = request.GetRequestStream();
    requestStream.Write(bytes, 0, bytes.Length);
    requestStream.Close();
    HttpWebResponse response;
    response = (HttpWebResponse)request.GetResponse();
    if (response.StatusCode == HttpStatusCode.OK)
    {
        Stream responseStream = response.GetResponseStream();
        string responseStr = new StreamReader(responseStream).ReadToEnd();
        return responseStr;
    }
    return null;
}

In your specific situation:

在您的具体情况下:

Instead of:

代替:

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

use:

用:

request.ContentType = "text/xml; encoding='utf-8'";

Also, remove:

另外,删除:

string postData = "XMLData=" + Sendingxml;

And replace:

并替换:

byte[] byteArray = Encoding.UTF8.GetBytes(postData);

with:

和:

byte[] byteArray = Encoding.UTF8.GetBytes(Sendingxml.ToString());

回答by ClaytonQ

AlliterativeAlice's example helped me tremendously. In my case, though, the server I was talking to didn't like having single quotes around utf-8in the content type. It failed with a generic "Server Error"and it took hours to figure out what it didn't like:

AllliterativeAlice 的例子对我帮助很大。但是,就我而言,我与之交谈的服务器不喜欢utf-8在内容类型中使用单引号。它因通用"Server Error"而失败,并且花了几个小时才弄清楚它不喜欢什么:

request.ContentType = "text/xml; encoding=utf-8";