1

我目前正在研究一些制作 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>

这需要转换为类对象 - 但我不确定如何以正确的方式进行。

任何建议表示赞赏。

4

1 回答 1

3

您想将返回的 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 ;
    }
于 2013-05-04T17:23:16.140 回答