c# - 如何使用 HttpWebRequest 以 XML 格式发送请求正文
问题描述
我是 API 新手。我有一个休息 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;
}
}
}
从这个答案
我正在做以下事情 -
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());
推荐阅读
- reactjs - Redux Store 在 getInitialProps 中填充,但在客户端为空
- python - Python Scrapy - 从 url 抓取的不是 start_urls 中设置的
- flutter - 在没有 SetState 的情况下调用持久性底页(使用 StreamBuilder)
- python - 如何将列表列表转换为字节?
- php - If Else with isset: else 部分不起作用 [PHP]
- javascript - 谷歌浏览器片段:标识符“...”已被声明
- r - 为相关矩阵选择变量
- c# - console.writeline 数组的值在一行上
- jakarta-ee - Jeddict 可以安装在 Netbeans 11 上吗?
- functional-programming - 重载函数的 Hindley-Milner 类型推断