阻止HttpWebRequest检查我的有效负载

时间:2016-01-04 14:23:31

标签: c# http httpwebrequest json-rpc

我需要将自定义有效负载发送到网络服务器,我使用HttpWebRequest来执行此操作。就我而言,它是一个json-rpc。我发送的内容并不重要,只要它不是像html表单或邮件附件那样编码数据。

请参阅我的代码:

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());

很简单。但是C#不喜欢有效载荷的内容,并在调用System.Net.ProtocolViolationException时抛出request.GetRequestStream().Write。我甚至无法启动请求!

为什么C#会查看有效负载的内容,如何阻止它?

1 个答案:

答案 0 :(得分:3)

如果要写入请求流,请确保使用的某些动词与GET不同。 POST可能是将数据发送到Web服务器的理想选择。

request.Method = "POST";

如果您没有明确指定HTTP动词,则假设GET解释了您收到错误的原因。

另外,您可以考虑在IDisposable语句中包装using资源,以使您的代码更好。更不用说可能值得摆脱的未使用的webClient变量:

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();