I need to send custom payloads to a webserver and I use HttpWebRequest for doing this. In my case, it is a json-rpc. I thing it does not matter what I send, as long as it isnt form-data encoded like in html forms or the attachments of mails.
See my code:
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://192.168.0.108/api/homematic.cgi");
byte[] rpc_request = Encoding.ASCII.GetBytes("{ \"method\": \"Session.login\", \"params\": [ \"username\": \"root\", \"password\": \"root\" ], \"id\": null}");
request.ContentLength = rpc_request.Length;
request.ContentType = "application/json";
using (var stream = request.GetRequestStream())
stream.Write(rpc_request, 0, rpc_request.Length);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Console.WriteLine("Status Code = {0}", response.StatusCode);
Console.WriteLine(new StreamReader(response.GetResponseStream()).ReadToEnd());
Very simple. But C# does not like the content of the payload and throws a System.Net.ProtocolViolationException
when calling request.GetRequestStream().Write
. I cant even start the request!
Why does C# look at the content of the payload at all and how can I stop it?
If you want to write to the request stream make sure that you are using some verb different than a GET
. A POST
could be a good candidate for sending data to a web server.
request.Method = "POST";
If you don't explicitly specify the HTTP verb, then GET
is assumed which explains why you are getting an error.
Also you might consider wrapping IDisposable
resources in using
statements just to make your code a lil'bit better. Not to mention the unused webClient
variable that might be worth getting rid of:
var request = (HttpWebRequest)WebRequest.Create("http://192.168.0.108/api/homematic.cgi");
string requestBody = "{ \"method\": \"Session.login\", \"params\": [ \"username\": \"root\", \"password\": \"root\" ], \"id\": null}";
request.ContentType = "application/json";
request.Method = "POST";
using (var stream = request.GetRequestStream())
using (var writer = new StreamWriter(stream))
{
stream.Write(requestBody);
}
using (var response = (HttpWebResponse)request.GetResponse())
using (var stream = response.GetResponseStream())
using (var reader = new StreamReader(stream))
{
Console.WriteLine("Status Code = {0}", response.StatusCode);
Console.WriteLine(reader.ReadToEnd());
}
Console.ReadLine();