我目前正在研究使httppost得到响应的一些功能。
以下是我目前正在使用的代码:
public string SubmitRequest(string postUrl, string contentType, string postValues)
{
var req = WebRequest.Create(postUrl);
req.Method = "POST";
req.ContentType = contentType;
try
{
using (var reqStream = req.GetRequestStream())
{
var writer = new StreamWriter(reqStream);
writer.WriteLine(postValues);
}
var resp = req.GetResponse();
using (var respStream = resp.GetResponseStream())
{
var reader = new StreamReader(respStream);
return reader.ReadToEnd().Trim();
}
}
catch(WebException ex)
{
// do something here
}
return string.Empty;
}
该函数以字符串格式返回xml,例如:
<result>
<code>Failed</code>
<message>Duplicate Application</message>
</result>
这需要转换为类对象 - 但我不确定如何以正确的方式进行。
任何建议表示赞赏。
答案 0 :(得分:2)
您希望将返回的xml反序列化为对象。这是一个基本的例子:
//m is the string based xml representation of your object. Make sure there's something there
if (!string.IsNullOrWhiteSpace(m))
{
//Make a new XMLSerializer for the type of object being created
var ser = new XmlSerializer(typeof(yourtype));
//Deserialize and cast to your type of object
var obj = (yourtype)ser.Deserialize(new StringReader(m));
return obj ;
}