从.net发送HttpWebRequest到php站点时出错

本文关键字:站点 出错 php net 发送 HttpWebRequest | 更新日期: 2023-09-27 18:08:32

尽管尝试了很多方法(见下文),我还是无法摆脱"写入流的字节超过指定的Content-Length字节大小。"

抛出的错误
writer.Close();

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

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。任何帮助是非常感激的,也有任何提示,我可以找到一个完美的工作脚本,张贴到php从ASP。. NET(服务器端).

从.net发送HttpWebRequest到php站点时出错

use

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

request.ContentLength = bdata.Length;

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