【问题标题】:Error when sending HttpWebRequest from .NET to php site将 HttpWebRequest 从 .NET 发送到 php 站点时出错
【发布时间】:2011-11-15 05:01:33
【问题描述】:

尽管尝试了很多事情(见下文),但我无法摆脱 “要写入流的字节超过指定的 Content-Length 字节大小。” 引发的错误

writer.Close();

这是尝试将数据从 ASP.NET 发布到 php 站点的代码。 只要代码中没有特殊字符,脚本就可以正常工作 - 请注意“Wörld”中的德语变音符号。

Uri uri = new Uri("http://mydomain/test.php");
string data = @"data=Hello Wörld";

HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(uri);
request.Method = WebRequestMethods.Http.Post;
request.ContentLength = data.Length;
request.ContentType = "application/x-www-form-urlencoded";
StreamWriter writer = new StreamWriter(request.GetRequestStream()); 
writer.Write(data);
writer.Close();
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
StreamReader reader = new StreamReader(response.GetResponseStream()); 
string tmp = reader.ReadToEnd();
response.Close();
Response.Write(tmp);

我尝试过使用 UTF-8 编码的不同变体,例如:

request.ContentLength = System.Text.Encoding.UTF8.GetByteCount(data);

和/或

StreamWriter writer = new StreamWriter(request.GetRequestStream(), Encoding.UTF8);

我也尝试在发送数据之前将其转换为 UTF-8(有点丑):

data = System.Text.Encoding.UTF8.GetString(System.Text.Encoding.Convert(System.Text.Encoding.UTF8, System.Text.Encoding.UTF8, System.Text.Encoding.UTF8.GetBytes(data)));

但错误仍然存​​在。我的感觉是我只是没有正确处理 UTF-8。非常感谢任何帮助,以及任何提示,我可以在其中找到从 ASP.NET(服务器端)发布到 php 的完美工作脚本。

【问题讨论】:

    标签: c# asp.net encoding utf-8


    【解决方案1】:

    使用

    byte[] bdata = Encoding.UTF8.GetBytes(data);
    

    request.ContentLength = bdata.Length;
    

    Stream writer = request.GetRequestStream(); 
    writer.Write(bdata, 0, bdata.Length);
    writer.Close();
    

    【讨论】:

    • 有时我真的希望我能给的不仅仅是一个赞成票和一个接受的答案。非常感谢您的快速回答,就像魅力一样,拯救了我的一天!
    猜你喜欢
    • 2012-01-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多