在通用应用程序中使用 POST 方法发送登录数据

send login data with POST method in a universal app

我在 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 应用程序的新手,请问您是否知道如何更正我的代码以将登录数据发送到服务器 感谢帮助

如您所见,WebRequest class in .NET Core is a little bit different than traditional .NET. First of all, I suggest you to look at the HttpClient class 这是 UWP 中使用 HTTP 的默认值 class。

如果要使用 WebRequest,为了设置 Content-Length header,请使用 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)) {
         //
     }
   }
}