2011-06-02 75 views
2

我在C#的客户,我有以下代码:问题发送POST变量与C#客户端

Uri uri = new Uri(@"http://myserver/test.php"); 
HttpWebRequest request = WebRequest.Create(uri) as HttpWebRequest; 
request.Method = WebRequestMethods.Http.Post; 
//request.ContentType = "application/json"; 

string req = "er3=12"; 
Console.WriteLine("Req: " + req); 

System.Text.ASCIIEncoding encoder = new System.Text.ASCIIEncoding(); 

byte[] byteData = encoder.GetBytes(req); 
request.ContentLength = byteData.Length; 

using (Stream postStream = request.GetRequestStream()) 
{ 
    postStream.Write(byteData, 0, byteData.Length); 
} 

这是调用PHP测试页面(即将休止服务代替):

<?php 
    echo "post vars:<br>"; 
    foreach ($_POST as $key => $value) { 
    echo "$key -> $value<br>"; 
    } 
    echo "end post vars:<br>"; 
?> 

我的问题是,当我运行应用程序,在我得到"post vars:<br>end post vars:<br>"的响应,所以变量er3没有收到。

如果我运行一个简单的html表单,post变量IS被正确读取。

C#代码中可能出错或丢失了什么?

感谢

+0

我看不到您在HTTP标头中指定编码的位置。 PHP页面是否需要ASCII编码? – 2011-06-02 15:32:26

回答

2

你需要设置你的数据的内容类型,这样PHP知道如何解析它。

像这样:

request.ContentType = "application/x-www-form-urlencoded"; 

application/x-www-form-urlencoded是发布表单数据时所使用的网络浏览器的标准MIME类型。