Execute XML-RPC call and return XML response as string


/ Published in: C#
Save to your folder(s)

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


Copy this code and paste it in your HTML
  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. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.