我不断收到以下错误消息之一:
"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 header 中设置字符集
req.ContentType = "application/x-www-form-urlencoded; charset=ASCII";
您还应该在实例化 StreamWriter 时指定编码:
new StreamWriter(req.GetRequestStream(), Encoding.ASCII)
关于c# - HttpRequest 和 POST,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7124797/