将xml请求发送到url并接收xml响应

时间:2015-03-08 21:25:03

标签: c# asp.net-mvc xmlhttprequest httpwebrequest

我尝试向网址发送xml请求,响应也是xml响应。我知道如何从MVC应用程序调用服务端点,但我不知道如何调用此URL以及如何阅读它将给我回复的内容。这就是我到目前为止所拥有的。这是正确的方向吗?

请求:

<CityStateLookupRequest USERID=”xxxxxxxx”>
<ZipCode ID="0">
<Zip5>90210</Zip5>
</ZipCode>
</CityStateLookupRequest>

回应:

<CityStateLookupResponse>
<ZipCode ID="0">
<Zip5>90210</Zip5>
<City>BEVERLY HILLS</City>
<State>CA</State>
</ZipCode>
</CityStateLookupResponse>

C#代码:

var xmlRequest = new XElement("CityStateLookupRequest",
                new XAttribute("USERID", "XXXXXXXXX"),
                new XElement("ZipCode",
                    new XAttribute("ID", "0"),
                    new XElement("Zip5", "43065")));    

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(" http://production.shippingapis.com/ShippingAPI.dll");

byte[] bytes = System.Text.Encoding.ASCII.GetBytes(xmlRequest.ToString());
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 = (HttpWebResponse)request.GetResponse();

if (response.StatusCode == HttpStatusCode.OK)
{
    var xmlDoc = new XmlDocument();

    xmlDoc.Load(response.GetResponseStream());
}

1 个答案:

答案 0 :(得分:2)

这是你可以做到这一点的一种方式,基本上是一个表格帖子。

var xmlRequest = new XElement("CityStateLookupRequest",
    new XAttribute("USERID", "XXXXXXXXX"),
    new XElement("ZipCode",
        new XAttribute("ID", "0"),
        new XElement("Zip5", "43065")));

HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://production.shippingapis.com/ShippingAPI.dll");        

// parameters to post - other end expects API and XML parameters
var postData = new List<KeyValuePair<string, string>>();
postData.Add(new KeyValuePair<string, string>("API", "CityStateLookup"));
postData.Add(new KeyValuePair<string, string>("XML", xmlRequest.ToString()));    

// assemble the request content form encoded (reference System.Net.Http)
HttpContent content = new FormUrlEncodedContent(postData);

// indicate what we are posting in the request
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = content.Headers.ContentLength.Value;
content.CopyToAsync(request.GetRequestStream()).Wait();                        

// get response
HttpWebResponse response = (HttpWebResponse)request.GetResponse();

if (response.StatusCode == HttpStatusCode.OK)
{
    // as an xml: deserialise into your own object or parse as you wish
    var responseXml = XDocument.Load(response.GetResponseStream());
    Console.WriteLine(responseXml.ToString());
}