我一直收到以下错误消息之一:
"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();发布于 2011-08-20 01:06:50
有几件事是“关”的:
直接写到你的写入器,不应该有理由调用GetBytes()。StreamWriter完全能够将字符串写入到流中:
writer.Write(bld.ToString());在StreamWriter周围使用() {}模式
这将确保正确处理编写器对象。
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)发布于 2011-08-20 01:06:11
req.ContentLength = bld.Length;
StreamWriter writer = new StreamWriter(req.GetRequestStream());
var encodedData = Encoding.ASCII.GetBytes(bld.ToString());
writer.Write(encodedData);你写的不是你说要写的东西--你写的是ASCII编码的字节,而不是原始的字节数组-- ContentLength必须与你写的字节数相匹配。取而代之的是:
var encodedData = Encoding.ASCII.GetBytes(bld.ToString());
req.ContentLength = encodedData.Length;https://stackoverflow.com/questions/7124797
复制相似问题