您的位置:首页 > 理论基础 > 计算机网络

WindowsPhone8 httpWebRequst 用Post方式向服务器端发送数据 服务器端使用php

2014-03-03 13:43 751 查看

做一个将textBox中的文本传送给服务器,然后服务器上的php文件将之储存至数据库中的应用

下面是代码。

private void launch_Click(object sender, RoutedEventArgs e)
{
string url = "http://asdf.com/SecondTest.php";//这里是php文件所在的位置
HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(url);
myRequest.Method = "POST";
myRequest.ContentType = "application/x-www-form-urlencoded";
myRequest.BeginGetRequestStream(getRequestCallBack, myRequest);
}

private void getRequestCallBack(IAsyncResult result)
{
HttpWebRequest request = (HttpWebRequest)result.AsyncState;
Dispatcher.BeginInvoke(() =>//之所以使用beginInvoke的意义在于下面读取了一个TextBox的Text属性,在WP8中需要使用这个
{
string postStr = "textContent=" + newTextMessage.Text;
using (Stream stream = request.EndGetRequestStream(result))
{

Byte[] postByte;
postByte = Encoding.UTF8.GetBytes(postStr);
stream.Write(postByte, 0, postByte.Length);
}
});

request.BeginGetResponse(ResponseCallback, request);

//返回应答请求异步操作的状态

}
//下面是从服务器获得数据,以此来检验是否传上去了,当然了,服务器要echo出刚才传入的东西
private void ResponseCallback(IAsyncResult result)
{
string response = null;
Stream stream = null;

try
{
//获取异步操作返回的的信息
HttpWebRequest httpWebRequest = (HttpWebRequest)result.AsyncState;
//结束对 Internet 资源的异步请求
WebResponse webResponse = httpWebRequest.EndGetResponse(result);
stream = webResponse.GetResponseStream();
using (StreamReader sr = new StreamReader(stream))
{
response = sr.ReadToEnd();
}
}
catch { }
finally
{
if (stream != null)
{
stream.Close();
}
}

//这里不为空代表获得回复了
if (response != null)
{
//因为HttpWebRequest是异步,不在UI线程上。所以要改变UI线程上的控件属性就要用Dispatcher.BeginInvoke()。
Dispatcher.BeginInvoke(() =>
{
MessageBox.Show(response);
});
}

}
}


  放php代码在这儿:

<?php
header("Content-type:application/x-www-form-urlencoded; charset=utf-8");

$a=$_POST["userName"];//以此来接收POST得到的数据

$con=mysql_connect("localhost","verssageli","password");
mysql_query("set character set 'utf-8'");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("verssageli",$con);
mysql_query("INSERT INTO postcontent (username) VALUES ('$a')");//向postcontent表中的username栏插入$a的值
echo $a;//输出$a

mysql_close($con);
?>


  
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: