C# 通过httpwebrequest发布数据并在php中获取
我在服务器中有以下php代码:C# 通过httpwebrequest发布数据并在php中获取,c#,php,httpwebrequest,C#,Php,Httpwebrequest,我在服务器中有以下php代码: foreach($_POST as $pdata) echo " *-* ". $pdata." *-*<br> "; 显示php页面的静态html代码。 但是messagebox中没有显示任何已发布的值。这意味着没有发布任何数据。 怎么了?您需要获取数据的字节数 请尝试此代码,从 你的PHP代码看起来不错。不知道c#。我想这是因为您没有指定请求正文的任何内容长度。 HttpWebRequest httpWebRequest
foreach($_POST as $pdata)
echo " *-* ". $pdata." *-*<br> ";
显示php页面的静态html代码。
但是messagebox中没有显示任何已发布的值。这意味着没有发布任何数据。
怎么了?您需要获取数据的字节数 请尝试此代码,从
你的PHP代码看起来不错。不知道c#。我想这是因为您没有指定请求正文的任何内容长度。
HttpWebRequest httpWebRequest = HttpWebRequest.Create("http://127.0.0.1/22") as HttpWebRequest;
//Specifing the Method
httpWebRequest.Method = "POST";
//Data to Post to the Page, itis key value pairs; separated by "&"
string data = "Username=username&password=password";
//Setting the content type, it is required, otherwise it will not work.
httpWebRequest.ContentType = "application/x-www-form-urlencoded";
//Getting the request stream and writing the post data
using (StreamWriter sw = new StreamWriter(httpWebRequest.GetRequestStream()))
{
sw.Write(data);
}
//Getting the Respose and reading the result.
HttpWebResponse httpWebResponse = httpWebRequest.GetResponse() as HttpWebResponse;
using (StreamReader sr = new StreamReader(httpWebResponse.GetResponseStream()))
{
MessageBox.Show(sr.ReadToEnd());
}
public string Post(string url, string data) {
string vystup = null;
try
{
//Our postvars
byte[] buffer = Encoding.ASCII.GetBytes(data);
//Initialisation, we use localhost, change if appliable
HttpWebRequest WebReq = (HttpWebRequest)WebRequest.Create(url);
//Our method is post, otherwise the buffer (postvars) would be useless
WebReq.Method = "POST";
//We use form contentType, for the postvars.
WebReq.ContentType = "application/x-www-form-urlencoded";
//The length of the buffer (postvars) is used as contentlength.
WebReq.ContentLength = buffer.Length;
//We open a stream for writing the postvars
Stream PostData = WebReq.GetRequestStream();
//Now we write, and afterwards, we close. Closing is always important!
PostData.Write(buffer, 0, buffer.Length);
PostData.Close();
//Get the response handle, we have no true response yet!
HttpWebResponse WebResp = (HttpWebResponse)WebReq.GetResponse();
//Let's show some information about the response
Console.WriteLine(WebResp.StatusCode);
Console.WriteLine(WebResp.Server);
//Now, we read the response (the string), and output it.
Stream Answer = WebResp.GetResponseStream();
StreamReader _Answer = new StreamReader(Answer);
vystup = _Answer.ReadToEnd();
//Congratulations, you just requested your first POST page, you
//can now start logging into most login forms, with your application
//Or other examples.
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
return vystup.Trim()+"\n";
}