访问XML RPC接口

时间:2014-11-18 15:09:14

标签: c# xml rpc xml-rpc

我有一些服务器与rtorrent。我想获取有关这些服务器的状态信息,并删除我要使用rtorrent的XML rpc接口的种子。

scgi_port = localhost:5000 https://github.com/rakshasa/rtorrent/wiki/RPC-Setup-XMLRPC

现在我需要一些帮助才能将界面信息传回我的程序。 我已经有了一些代码,但执行时总是会出错。

其他信息:无法建立与远程服务器的连接。

using System;
using System.Text;
using System.Net;
using System.IO;

namespace SimpleXmlRpcClient
{
    class Program
    {
        static void Main(string[] args)
        {
            WebRequest request = WebRequest.Create("http://ip/RPC2");
            request.Method = "POST";
            string postData = @"<?xml version=""1.0""?>
            <methodCall>
              <methodName>system.listMethods
            </methodCall>";
            byte[] byteArray = Encoding.UTF8.GetBytes(postData);
            request.ContentType = "application/x-www-form-urlencoded";
            request.ContentLength = byteArray.Length;
            Stream dataStream = request.GetRequestStream();
            dataStream.Write(byteArray, 0, byteArray.Length);
            dataStream.Close();
            WebResponse response = request.GetResponse();
            Console.WriteLine(((HttpWebResponse)response).StatusDescription);
            dataStream = response.GetResponseStream();
            StreamReader reader = new StreamReader(dataStream);
            string responseFromServer = reader.ReadToEnd();
            Console.WriteLine(responseFromServer);
            reader.Close();
            dataStream.Close();
            response.Close();
            Console.WriteLine("Press any key to continue ...");
            Console.ReadKey();
        }
    }
}

2 个答案:

答案 0 :(得分:1)

我终于找到了解决方案。

你仍然解析了xml编码的响应,但现在我终于得到了响应。

System.Net.ServicePointManager.Expect100Continue = false;
                byte[] requestData = Encoding.ASCII.GetBytes("<?xml version=\"1.0\"?><methodCall><methodName>system.listMethods</methodName></methodCall>");

                HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://ip/RPC2");
                request.Method = "POST";
                request.UserAgent = "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0; .NET CLR 1.1.4322; .NET CLR 2.0.50727; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729;)";
                request.ContentType = "text/xml";
                request.ContentLength = requestData.Length;

                using (Stream requestStream = request.GetRequestStream())
                    requestStream.Write(requestData, 0, requestData.Length);

                string result = null;
                using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
                {
                    using (Stream stream = response.GetResponseStream())
                    {
                        using (StreamReader reader = new StreamReader(stream, Encoding.ASCII))
                            result = reader.ReadToEnd();
                    }
                }

答案 1 :(得分:0)

好的! ,奥利亚斯的解决方案是正确的。