我正在使用Windows应用商店,我正在尝试发送登录名和密码值,这是我的代码:
try
{
string user = login.Text;
string pass = password.Password;
ASCIIEncoding encoding = new ASCIIEncoding();
string postData = "login=" + user + "&mdp=" + pass;
byte[] data = encoding.GetBytes(postData);
WebRequest request = WebRequest.Create("myURL/login.php");
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = data.Length;
Stream stream = request.GetRequestStream();
stream.Write(data, 0, data.Length);
stream.Dispose();
WebResponse response = request.GetResponse();
stream = response.GetResponseStream();
StreamReader sr = new StreamReader(stream);
sr.Dispose();
stream.Dispose();
}
catch (Exception ex)
{
ex.Message.ToString();
}
我有很多这样的错误:
'WebRequest' does not contain a definition for 'Content Length' and no extension method 'ContentLength' accepting a first argument of type 'WebRequest' was found (a using directive or an assembly reference is she missing ?)
'WebRequest' does not contain a definition for 'GetRequestStream' and no extension method 'GetRequestStream' accepting a first argument of type 'WebRequest' was found (a using directive or an assembly reference is she missing? )
'WebRequest' does not contain a definition for 'GetResponse' and no extension method 'GetResponse' accepting a first argument of type 'WebRequest' was found (a using directive or an assembly reference is she missing? )
我是通用Windows应用程序的新手,所以请您知道如何更正我的代码以将登录数据发送到服务器 谢谢你的帮助
答案 0 :(得分:6)
正如您所注意到的,.NET Core中的WebRequest类与传统.NET略有不同。首先,我建议您查看HttpClient类,它是UWP中用于处理HTTP的默认类。
如果您想使用WebRequest,为了设置Content-Length标头,请使用Headers属性:
request.Headers["ContentLength"] = length;
为了获取请求和响应流,您需要使用async方法,GetRequestStreamAsync和GetResponseAsync。同步方法不可用。
毕竟你的代码看起来像这样:
string user = login.Text;
string user = login.Text;
string pass = password.Password;
ASCIIEncoding encoding = new ASCIIEncoding();
string postData = "login=" + user + "&mdp=" + pass;
byte[] data = encoding.GetBytes(postData);
WebRequest request = WebRequest.Create("myURL/login.php");
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.Headers["ContentLength"] = data.Length.ToString();
using (Stream stream = await request.GetRequestStreamAsync()) {
stream.Write(data, 0, data.Length);
}
using (WebResponse response = await request.GetResponseAsync()) {
using (Stream stream = response.GetResponseStream()) {
using (StreamReader sr = new StreamReader(stream)) {
//
}
}
}