阻止 HttpWebRequest 检查我的负载

Stop HttpWebRequest from checking my payload

我需要将自定义负载发送到网络服务器,我使用 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#不喜欢payload的内容,调用request.GetRequestStream().Write的时候会抛出一个System.Net.ProtocolViolationException。我什至无法开始请求!

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

如果您想写入请求流,请确保您使用的动词不同于 GETPOST 可能是将数据发送到 Web 服务器的理想选择。

request.Method = "POST";

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

您也可以考虑在 using 语句中包装 IDisposable 资源,只是为了让您的代码稍微好一点。更不用说可能值得摆脱的未使用的 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();