Windows Phone中的$ .post等价物

时间:2014-07-03 07:33:45

标签: c# windows-phone-8 webclient

  $.post(loginurl, {username: $username, password: $password}, function(response) {

            if (response.session_id === null) {
                // alert("Please enter correct credentials!");
                return;
            }

写了这个,但没有得到任何结果:

   //POST


      WebClient clt = new WebClient();
            var JsonLoginString = JsonConvert.SerializeObject(credentials);

            clt.Headers["Content-Type"] = "application/json";


            string check = "username:"+username+"password:"+password;


            clt.UploadStringAsync(new Uri(Config.loginurl), check);
            clt.UploadStringCompleted += clt_UploadStringCompleted;
  private void clt_UploadStringCompleted(object sender, UploadStringCompletedEventArgs e)
        {

        }

编辑:

我试过用这个:

  public void Login(string username, string password)
    {
        var request = (HttpWebRequest)WebRequest.Create(Config.loginurl);
        request.ContentType = "application/json";
        request.Method = "POST";
        request.BeginGetRequestStream(new AsyncCallback(GetRequestCallBack), request);



    }

    private void GetRequestCallBack(IAsyncResult ar)
    {
        string username = "admin@something.com";
        string password = "admin";
        HttpWebRequest request = (HttpWebRequest)ar.AsyncState;
        Stream postStream = request.EndGetRequestStream(ar);
        Byte[] byteData = Encoding.UTF8.GetBytes("username:"+username+"password:"+password);
        postStream.Write(byteData, 0, byteData.Length);
        postStream.Close();

        request.BeginGetResponse(new AsyncCallback(GetResponseCallBack), request);

    }
    string recMessage = "";
    private void GetResponseCallBack(IAsyncResult ar)
    {
        HttpWebRequest request = (HttpWebRequest)ar.AsyncState;
        using (var response = request.EndGetResponse(ar))
        using (var reader = new StreamReader(response.GetResponseStream()))
        {
            Deployment.Current.Dispatcher.BeginInvoke(() =>
            {
                SendData();
            });
            recMessage = reader.ReadToEnd();
        }

    }

    private void SendData()
    {
        MessageBox.Show(recMessage.ToString());
    }

1 个答案:

答案 0 :(得分:1)

HttpClient可以帮到你。 This is the Nuget package

using (var client = new HttpClient())
{
    client.BaseAddress = new Uri("http://www.url.com/");
    client.Content = new StringContent(jsonEncodedCredentials, Encoding.UTF8, "application/json"))

    HttpResponseMessage response = await client.PostAsync("api/login");
    if (response.IsSuccessStatusCode)
    {
        string jsonEncodedReponse = await response.Content.ReadAsStringAsync();
        //Do something with the response

    }
}