简体   繁体   中英

call REST API in xamarin

I design a login form in xamarin Form PCL and I want to call a my webservice that will return JSON. For this, I created two functions for the same but both are n is not returning values.

Can you please tell me what I am doing wrong?

async void OnLoginButtonClick(object sender, EventArgs e)
    {
        if (usernameEntry.Text != "" && passwordEntry.Text != "")
        {
             var response = GetLoginDetails(usernameEntry.Text,passwordEntry.Text);
              var getData = await getDataFromService(usernameEntry.Text, passwordEntry.Text);

        }

    }

 public static async Task<HttpResponseMessage> GetLoginDetails(string username, string password)
    {
      try
        {
            var httpClient = new HttpClient();
            HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, "http://mywebserverIP/api/Users?Username=" + username + "&Password=" + password);
            var response = await httpClient.SendAsync(request);
            return response;


        }
        catch (Exception ex)
        {

            throw;
        }
    }

public static async Task<dynamic> getDataFromService(string username, string password)
    {
        using (var client = new HttpClient())
        {
            var responseText = await client.GetStringAsync("http://mywebserverIP/api/Users?Username=" + username + "&Password=" + password);
            dynamic data = JsonConvert.DeserializeObject(responseText);
            return data;
        }

    }

Thanks for your comment in Advance.

As you not awaiting the first method , request thread will not wait till it returns the value so , 1st change you have to make is to

var response = await GetLoginDetails()

For the second method

var getData = await getDataFromService()

I do not see any issue. I am not sure how you know that this method is not returning any values. Better to log the response of the both the method call and check.

Use await. First in the

var response = await GetLoginDetails(...

then maybe in the deserializeobject method too (this one i'm not sure)

dynamic data = await Task.Run(() => JsonConvert.DeserializeObject(responseText));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM