HttpRequest 和 POST

2023-12-01

我不断收到以下错误消息之一:

"The remote server returned an error: (400) Bad Request."  
               OR
"System.Net.ProtocolViolationException: You must write ContentLength bytes to the request stream before calling [Begin]GetResponse."

这是我正在运行的代码:

        StringBuilder bld = new StringBuilder();
        bld.Append("contractId=");
        bld.Append(ctrId);
        bld.Append("&companyIds=");
        bld.Append("'" + company1+ ", " + company2+ "'");

        HttpWebRequest req = (HttpWebRequest)WebRequest
            .Create(secureServiceUrl + "SetContractCompanyLinks");
        req.Credentials = service.Credentials;
        //req.AllowWriteStreamBuffering = true;
        req.Method = "POST";
        req.ContentType = "application/x-www-form-urlencoded";
        req.ContentLength = bld.Length;
        StreamWriter writer = new StreamWriter(req.GetRequestStream());
        var encodedData = Encoding.ASCII.GetBytes(bld.ToString());
        writer.Write(encodedData);
        writer.Flush();
        writer.Close();
        var resp = req.GetResponse();

有几件事是“关闭”的:

直接写信给你的作家不应该有理由调用 GetBytes()。 StreamWriter 完全能够将字符串写入流:

writer.Write(bld.ToString());

在 StreamWriter 周围使用 using() {} 模式

这将确保正确处理 writer 对象。

using(var writer = new StreamWriter(req.GetRequestStream()))
{
   writer.Write(bld.ToString());
}

您不需要显式设置内容长度不用管它,框架会根据您写入请求流的内容为您设置它。

如果您需要明确使用 ASCII,请在 Content-Type 标头中设置字符集

req.ContentType = "application/x-www-form-urlencoded; charset=ASCII";

您还应该在实例化 StreamWriter 时指定编码:

new StreamWriter(req.GetRequestStream(), Encoding.ASCII)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

HttpRequest 和 POST 的相关文章

随机推荐