执行XML-RPC调用并以字符串形式返回XML响应

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了执行XML-RPC调用并以字符串形式返回XML响应相关的知识,希望对你有一定的参考价值。

This method can execute XML-RPC call and return response. Can be useful for working with XML-RPC API's like Snipplr.com XML-RPC API and other
  1. /// <summary>
  2. /// Execute XML-RPC request and returns XML response as string
  3. /// </summary>
  4. /// <param name="uri">URL for request, for examle: "http://snipplr.com/xml-rpc.php"</param>
  5. /// <param name="methodName">Name of method to be called, for example: snippet.list</param>
  6. /// <param name="parameters">Optional parameters for the method.
  7. /// Can be null or must have members of following types: short, int, bool, double, string, DateTime
  8. /// </param>
  9. /// <returns>String than contains XML response of method</returns>
  10. public static string XmlRpcExecMethod(string uri, string methodName, List<Object> parameters)
  11. {
  12. var req = (HttpWebRequest)WebRequest.Create(uri);
  13. req.Method = "POST";
  14. var genParams = "";
  15. if (parameters != null && parameters.Count > 0)
  16. {
  17. foreach (var param in parameters)
  18. {
  19. if (param == null) continue;
  20. if (param.GetType().Equals(typeof (string)))
  21. {
  22. genParams += string.Format(@"<param><value><string>{0}</string></value></param>", param);
  23. }
  24. if (param.GetType().Equals(typeof(bool)))
  25. {
  26. genParams += string.Format(@"<param><value><boolean>{0}</boolean></value></param>", (bool)param ? 1 : 0);
  27. }
  28. if (param.GetType().Equals(typeof(double)))
  29. {
  30. genParams += string.Format(@"<param><value><double>{0}</double></value></param>", param);
  31. }
  32. if (param.GetType().Equals(typeof(int)) || param.GetType().Equals(typeof(short)))
  33. {
  34. genParams += string.Format(@"<param><value><int>{0}</int></value></param>", param);
  35. }
  36. if (param.GetType().Equals(typeof (DateTime)))
  37. {
  38. genParams +=
  39. string.Format(
  40. @"<param><value><dateTime.iso8601>{0:yyyy}{0:MM}{0:dd}T{0:hh}:{0:mm}:{0:ss}</dateTime.iso8601></value></param>",
  41. param);
  42. }
  43. }
  44. }
  45. var command =
  46. @"<?xml version=""1.0""?><methodCall><methodName>" + methodName +
  47. @"</methodName><params>" + genParams + @"</params></methodCall>";
  48. var bytes = Encoding.ASCII.GetBytes(command);
  49. req.ContentLength = bytes.Length;
  50. using (var stream = req.GetRequestStream())
  51. {
  52. stream.Write(bytes, 0, bytes.Length);
  53. }
  54.  
  55. using (var stream = new StreamReader(req.GetResponse().GetResponseStream()))
  56. {
  57. return stream.ReadToEnd();
  58. }
  59. }

以上是关于执行XML-RPC调用并以字符串形式返回XML响应的主要内容,如果未能解决你的问题,请参考以下文章

XML-RPC远程方法调用

XML-RPC 从响应中获取值

如何处理 XML-RPC 中的错误响应?

使用xml-rpc调试openerp模块中的函数

如何覆盖 Laminas XML-RPC 服务器响应的标头?

XML-RPC:如何使过程调用可以访问登录凭据?