Http将xml文件发布到外部URL,然后接收响应

时间:2019-06-11 06:48:41

标签: c# asp.net-mvc-5 http-post

我正在尝试将HTTP发布到外部URL并发送XML文件。我想通过我的MVC控制器执行此操作。我可以看到很多有关从MVC控制器接收XML文件的建议,但看不到任何有关发送的建议。我希望这是一个非常简单的请求,如果有人能指出正确的方向,我将不胜感激。

我已将我的xml文件创建为XDocument,并希望使用http post发送到第三方URL

然后,我必须从包含另一个xml文档的URL接收响应。

  1. 最初发送XDocument的命令是什么。
  2. 我是否创建一个具有相同名称但使用[HTTPPOST]过滤器的新控制器动作来接收响应?
  3. 响应参数是否应接受XDocument数据类型以接收返回的xml文档?

如果我走的路不正确,请告诉我。

非常感谢

2 个答案:

答案 0 :(得分:0)

  1. 如果您已经拥有XDocument,则可以调用.ToString(),它将为您提供XML字符串,以用作POST请求正文。

  2. 您可以使用HttpClient发出HTTP POST请求并处理响应(请参见示例)。

  3. 不确定您的意思吗?

根据https://docs.microsoft.com/en-us/dotnet/api/system.net.http.httpclient?view=netframework-4.8改编的示例:

XDocument xDocument = XDocument.Parse("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n<note>\r\n  <to>Tove</to>\r\n  <from>Jani</from>\r\n  <heading>Reminder</heading>\r\n  <body>Don't forget me this weekend!</body>\r\n</note>");

string xmlRequestBody = xDocument.ToString();

// Create a New HttpClient object and dispose it when done, so the app doesn't leak resources
using (HttpClient client = new HttpClient())
{
    // Call asynchronous network methods in a try/catch block to handle exceptions
    try 
    {
        HttpResponseMessage response = await client.PostAsync("your_external_url", new StringContent(xmlRequestBody, Encoding.UTF8, "text/xml")));

        response.EnsureSuccessStatusCode();

        // responseBody will contain the response XML document (hopefully!)
        string responseBody = await response.Content.ReadAsStringAsync();

        // parse the string into an XDocument
        XDocument responseDocument = XDocument.Parse(responseBody);

        Console.WriteLine(responseBody);
    }  
    catch (HttpRequestException e)
    {
        Console.WriteLine("\nException Caught!");   
        Console.WriteLine("Message :{0} ",e.Message);
    }
}

答案 1 :(得分:0)

尝试在请求正文中发送xml内容。

在xmlData参数中传递XML字符串

    private object ProcessResponse(string xmlData)
    {
        HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(URL);
        httpWebRequest.ContentType = "application/xml";
        httpWebRequest.Method = "POST";

        object result = null;
        if (!string.IsNullOrEmpty(xmlData))
        {
            byte[] data = Encoding.UTF8.GetBytes(xmlData);

            using (var stream = httpWebRequest.GetRequestStream())
            {
                stream.Write(data, 0, data.Length);
            }
        }

        HttpWebResponse httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();

        using (StreamReader streamReader = new StreamReader(httpResponse.GetResponseStream()))
        {
            result = JsonConvert.DeserializeObject(streamReader.ReadToEnd());
        }
        return result;
    }
相关问题