【发布时间】:2011-08-30 06:00:29
【问题描述】:
我不断收到以下错误消息之一:
"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();
【问题讨论】:
-
您的请求中一定有问题/缺失。您检查过应用程序日志是否有错误?
-
是的,我检查了它,但没有出现任何内容,可能是我没有配置好。我再检查一下。
-
这可能不是 400 响应的原因,但您应该 URLEncode
ctrId和"'" + company1+ ", " + company2+ "'" -
现在我遇到了异常:System.Net.ProtocolViolationException: 您必须在调用 [Begin]GetResponse 之前将 ContentLength 字节写入请求流。