Accessing XML RPC Interface - c#

i have some servers with rtorrent. I want to get status information about these servers and delete torrents for that i want to use the XML rpc interface of rtorrent.
scgi_port = localhost:5000
https://github.com/rakshasa/rtorrent/wiki/RPC-Setup-XMLRPC
Now i rly need some help to get the information from the interface back to my programm.
i already have some code, but i always get an error when executing.
Additional information: The Connection with the remote server could not be established.
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();
}
}
}

i finally found the solution.
you still have parse the xml encoded response but now i finally get an response.
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();
}
}

Good ! ,the solution of Olias is correct.

Related

How can i get cookies in web request using c#?

I'm new to c# language. I want to write this code to post data to web url:
byte[] data = Encoding.ASCII.GetBytes($"Identifier={"anyUsername"}&Password={"Password"}");
WebRequest request = WebRequest.Create("http://users.tclnet.ir/Authentication/LogOn");
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = data.Length;
using (Stream stream = request.GetRequestStream())
{
stream.Write(data, 0, data.Length);
}
string responseContent = null;
using (WebResponse response = request.GetResponse())
{
using (Stream stream = response.GetResponseStream())
{
using (StreamReader sr99 = new StreamReader(stream))
{
responseContent = sr99.ReadToEnd();
}
}
}
but i want get cookies from that answer,how can i write code to achieve it?

Get html source from internet meet some issue

I want to fetch a web page to analyze stock information. I use the following sample code to get html data using c#. While it compiles, running it always ends in an error.
The following is my sample code:
string urlAddress = "http://pchome.syspower.com.tw/stock/sto0/ock2/sid2404.html";
var request = (HttpWebRequest)WebRequest.Create(urlAddress);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = 1414;
var requestStream = request.GetRequestStream();
requestStream.Write(Encoding.UTF8.GetBytes("is_check=1"), 0, 10);
requestStream.Close();
var response = (HttpWebResponse)request.GetResponse();
var sr = new StreamReader(response.GetResponseStream());
string rawData = sr.ReadToEnd();
sr.Close();
response.Close();
Does anyone know how to solve this issue?
The errors were mostly related to the order of your code and the closing of Stream objects your were still going to use.
Also I recommend to use using where possible to correctly dispose objects.
Use this code:
string rawData;
byte[] bytes = Encoding.UTF8.GetBytes("is_check=1");
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(urlAddress);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = bytes.Length;
using (Stream requestStream = request.GetRequestStream())
{
requestStream.Write(bytes, 0, bytes.Length);
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
using (StreamReader sr = new StreamReader(response.GetResponseStream()))
{
rawData = sr.ReadToEnd();
}
}
}

C# Webrequest to Sockets

I have an application that starts multiple threads, and each thread sends requests to a remote server. After profiling, I noticed that the most time is taken in sending & processing the request. This is the function:
private string GetRequest(string url, string postFields)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Proxy = proxy;
request.AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip;
request.Host = Constants.URLDomain;
request.KeepAlive = true;
request.Accept = Constants.Accept;
request.ContentType = "application/json";
request.Headers.Add("MyHeader1", "true");
request.Headers.Add("MyHeader2", "header2value");
request.Headers.Add("MyHeader3", "header3value");
request.Method = "POST";
byte[] postBytes = Encoding.UTF8.GetBytes(postFields);
request.ContentLength = postBytes.Length;
using (Stream postStream = request.GetRequestStream())
{
postStream.Write(postBytes, 0, postBytes.Length);
}
string text = string.Empty;
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
using (Stream answer = response.GetResponseStream())
using (StreamReader reader = new StreamReader(answer, System.Text.Encoding.UTF8))
{
text = reader.ReadToEnd();
}
}
return text;
}
I was thinking of changing this code to use sockets so I could improve performance. Will there be actually an improvement if I change to sockets, and more importantly, how do will a sockets implementation of the above code look like?

OutOfMemoryException reading response stream

What could be causing an out of memory exception in the code below? My program was running for a few hours and then died. The code only sends/receives a very small amount of data each time, so there are no huge files or strings going over the wire or coming back. The code sends and receives from the server every 3 seconds or so.
private void Read()
{
string postData = "Name=John"
using (HttpWebResponse response = SendRequest(new Uri(#"someWebSitehere"), postData))
{
Stream stream = response.GetResponseStream();
StreamReader reader = new StreamReader(stream);
responseFromServer = reader.ReadToEnd();  IT THROWS OUT OF MEMORY HERE
  stream.Close();
}
}
private HttpWebResponse SendRequest(Uri uri, string postData)
{
lock (SendRequestLock)
{
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(uri);
req.Method = "POST";
req.CookieContainer = new CookieContainer();
req.Proxy = null;
UTF8Encoding encoding = new UTF8Encoding();
byte[] byte1 = encoding.GetBytes(postData);
// Set the content type of the data being posted.
req.ContentType = "application/x-www-form-urlencoded";
// Set the content length of the string being posted.
req.ContentLength = byte1.Length;
req.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; .NET CLR 1.0.3705;)";
req.Method = "POST";
req.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
req.Headers.Add("Accept-Language: en-us,en;q=0.5");
req.Headers.Add("Accept-Encoding: gzip,deflate");
req.Headers.Add("Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7");
req.KeepAlive = true;
req.Headers.Add("Keep-Alive: 300");
using (Stream stream = req.GetRequestStream())
{
stream.Write(byte1, 0, byte1.Length);
}
return (HttpWebResponse)req.GetResponse();
}
}
You'll want to dispose of the IDisposable classes Stream and StreamReader:
using (Stream stream = response.GetResponseStream())
{
using (StreamReader reader = new StreamReader(stream))
{
responseFromServer = reader.ReadToEnd();  //IT THROWS OUT OF MEMORY HERE
}
}
Classes that implement IDisposable generally have external resources that they will hang onto unless you call Dispose() (or, same thing, put it inside a using block). It's likely that those classes are leaking memory each time your block of code runs, hence the "out of memory" exception after some time.
It's worthwhile reading MSDN's notes on IDisposable.
Have you checked Content-Length of the response. Maybe it is very huge. In this case you should read response stream part by part

How to ignore reponse data from when send Post request?

I send Post request by follow code:
try
{
string responseContent;
request = (HttpWebRequest)WebRequest.Create(url);
request.CookieContainer = cookieContainer;
// Set Method to "POST"
request.Method = "POST";
// Set the content type of the WebRequest
request.ContentType = "application/x-www-form-urlencoded";
request.Proxy = GlobalProxySelection.GetEmptyWebProxy();
request.UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 6.1; de; rv:1.9.2.3) Gecko/20100401 Firefox/3.6.3";
// Set the content length
ASCIIEncoding encoding = new ASCIIEncoding();
byte[] byteArray = encoding.GetBytes(requestCommand);
request.ContentLength = byteArray.Length;
// Get the request stream
using (Stream requestStream = request.GetRequestStream())
{
// Write the "POST" data to the stream
requestStream.Write(byteArray, 0, byteArray.Length);
}
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
using (Stream responseStream = response.GetResponseStream())
{
using (BufferedStream buffer = new BufferedStream(responseStream))
{
using (StreamReader reader = new StreamReader(buffer))
{
responseContent = reader.ReadToEnd();
}
}
}
}
return responseContent;
}
catch (Exception ex)
{
return ex.Message;
}
}
It's works ok. But the code lines below is so slow.
using (StreamReader reader = new StreamReader(buffer))
{
responseContent = reader.ReadToEnd();
}
I don't know why! I have spend more time to find out solution, such at set proxy = null,... but no results.
Are there any way to ignore that line. I dont need to receive response data. I have tried replace that lines by:
using (Stream responseStream = response.GetResponseStream())
{
responseStream.Flush();
responseStream.Close();
}
But I can't send Post request correctly and sucessfuly. Please help me. Thanks so much!
If you don't care at all about the response or whether it fails, you can probably queue up the response on a new thread and just ignore it.
using (Stream requestStream = request.GetRequestStream())
{
// Write the "POST" data to the stream
requestStream.Write(byteArray, 0, byteArray.Length);
}
// now put the get response code in a new thread and immediately return
ThreadPool.QueueUserWorkItem((x) =>
{
using (var objResponse = (HttpWebResponse) request.GetResponse())
{
responseStream = new MemoryStream();
objResponse.GetResponseStream().CopyTo(responseStream);
responseStream.Seek(0, SeekOrigin.Begin);
}
});

Categories

Resources