如何使用HttpWebRequest以XML发送请求正文



我是API新手。我有一个rest API,它有一个XML格式的请求主体和响应主体。我想访问API,但我不知道如何从代码中发送请求主体。我的API的请求主体是-

<Person>
<Id>12345</Id>
<Customer>John Smith</Customer>
<Quantity>1</Quantity>
<Price>10.00</Price>
</Person>

我的努力:

到目前为止,我知道要处理API,必须创建一个代理类。所以我的代理类是-

[System.SerializableAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
[System.Xml.Serialization.XmlRootAttribute(Namespace = "", IsNullable = false)]
public partial class Person
{
private ushort idField;
private string customerField;
private byte quantityField;
private decimal priceField;
/// <remarks/>
public ushort Id
{
get
{
return this.idField;
}
set
{
this.idField = value;
}
}
/// <remarks/>
public string Customer
{
get
{
return this.customerField;
}
set
{
this.customerField = value;
}
}
/// <remarks/>
public byte Quantity
{
get
{
return this.quantityField;
}
set
{
this.quantityField = value;
}
}
/// <remarks/>
public decimal Price
{
get
{
return this.priceField;
}
set
{
this.priceField = value;
}
}
}

根据这个答案

如何使用HttpWebRequest发布数据?

我正在做以下事情-

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);

我在var data = Encoding.ASCII.GetBytes(person)中出错

上面写着cannot convert form Person to Char[]

我现在不知道该怎么办。

GetBytes期望类似字符串的输入将其转换为字节数组。因此,您必须首先将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());

最新更新