【发布时间】:2021-10-29 02:45:45
【问题描述】:
我发送一个 RestRequest 并接收 xml 格式的响应。 这是我的代码:
class Employee
{
int id;
string name;
}
private void reqEmployee(Employee empl)
{
var client = new RestClient(ConfigurationManager.AppSettings["base_url"] + "/" +
ConfigurationManager.AppSettings["provider"] + "/" +
ConfigurationManager.AppSettings["serviceName"])
{
Timeout = -1
};
var request = new RestRequest(Method.POST);
var authenticationString = string.Format("{0}:{1}", ConfigurationManager.AppSettings["serviceUser"], ConfigurationManager.AppSettings["servicePass"]);
var base64EncodedAuthenticationString = Convert.ToBase64String(System.Text.ASCIIEncoding.ASCII.GetBytes(authenticationString));
request.AddHeader("Authorization", "Basic " + base64EncodedAuthenticationString);
request.AddHeader("Content-Type", "text/plain");
var body = @"<GetEmployee xmlns=""http://test.dev.com/"">"
+ "\n" + @" <Id>" + empl.idno + "</Id>"
+ "\n" + @"</GetEmployee>";
request.AddParameter("text/plain", body, ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
}
我发送的请求示例:
<GetEmployee xmlns="http://test.dev.com/">
<Id>4132</Id>
</GetEmployee>
我收到的回复示例 (response.Content):
<GetEmployeeResponse xmlns="http://test.dev.com/">
<PropertyStatus xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<Employee>
<Name>John</Name>
<Id>6584</Id>
</Employee>
<Employee>
<Name>Chris</Name>
<Id>4120</Id>
</Employee>
</PropertyStatus>
</GetEmployeeResponse>
如何用response.Content 填写List<Employee>?
【问题讨论】:
-
这能回答你的问题吗? Building XML request with RestSharp
-
谢谢你的回答,这个链接是关于发送一个包含对象数组的请求,我只想读取响应并将其保存为员工数组
-
如果您在请求中设置了 DataFormat 和 Serializer,那么您可以调用
Execute<T>,您可以在其中指定List<Employee>作为预期输出。 -
这里是another SO thread,其中详细介绍了这个概念。