c# - HttpRequest 和 POST

标签 c# .net wcf

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

"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/

相关文章:

wcf - 使用 http 和 https 绑定(bind)/端点部署 WCF 服务

c# - 构建远距离查询数据库和程序的最佳方式

wcf - 从地址下载元数据时出错

c# - 在 C# restful web 服务中删除 xml 命名空间返回字符串

c# - JavaScript 运行时错误 :function expected ajax call

c# - Dispatcher.Invoke 是否在调用线程上阻塞?

.net - 如何清除 .NET 中文件的只读标志?

c# - 无法将图像转换为 bytes[] C#

c# - AppSettings 中的更改需要重新启动我的应用程序,我该如何避免?

c# - 如何将纯文本发送到 ASP.NET Web API 端点?