C# 如何使用HttpWebRequest以XML格式发送请求正文
我不熟悉API。我有一个RESTAPI,它有一个XML格式的请求体和响应体。 我想点击API,但我不知道如何从代码中发送请求体。 我的API的请求主体是-C# 如何使用HttpWebRequest以XML格式发送请求正文,c#,api,C#,Api,我不熟悉API。我有一个RESTAPI,它有一个XML格式的请求体和响应体。 我想点击API,但我不知道如何从代码中发送请求体。 我的API的请求主体是- <Person> <Id>12345</Id> <Customer>John Smith</Customer> <Quantity>1</Quantity> <Price>10.00</Price> </Person> 我
<Person>
<Id>12345</Id>
<Customer>John Smith</Customer>
<Quantity>1</Quantity>
<Price>10.00</Price>
</Person>
我在var data=Encoding.ASCII.GetBytes(person)
它说无法将表单Person转换为Char[]
我现在不知道如何继续。希望类似字符串的输入将其转换为字节数组。因此,您必须首先将peron
转换为字符串/字符数组。因为您想要使用XML,所以应该使用XML序列化程序。例如,使用.NET内置的序列化程序:
// Setup for the person above
// Serialize the person into an XML string
var serializer = new XmlSerializer(typeof(Person));
var sb = new StringBuilder();
using (XmlWriter xmlWriter = XmlWriter.Create(sb))
{
serializer.Serialize(xmlWriter, person);
}
// Byte array data to send
var data = Encoding.ASCII.GetBytes(sb.ToString());
var request = (HttpWebRequest)WebRequest.Create("https://reqbin.com/sample/post/xml");
Person person = new Person();
Console.WriteLine("Enter ID");
person.Id = Convert.ToUInt16(Console.ReadLine());
Console.WriteLine("Enter Name");
person.Customer = Console.ReadLine();
Console.WriteLine("Enter Quantity");
person.Quantity = Convert.ToByte(Console.ReadLine());
Console.WriteLine("Enter Price");
person.Price = Convert.ToDecimal(Console.ReadLine());
var data = Encoding.ASCII.GetBytes(person);
// Setup for the person above
// Serialize the person into an XML string
var serializer = new XmlSerializer(typeof(Person));
var sb = new StringBuilder();
using (XmlWriter xmlWriter = XmlWriter.Create(sb))
{
serializer.Serialize(xmlWriter, person);
}
// Byte array data to send
var data = Encoding.ASCII.GetBytes(sb.ToString());