Farid
Farid

Reputation: 1020

How to make https webAPI call?

I'm trying to make https webAPI call, specifically - Google Directions API. Putting the uri directly inside browser gives me the result that I want, so I'm 100% sure my uri is correct.

Now, how do I call the webapi inside my PCL? Using modernhttp and HttpClient now, but am open to whatever options there are out there.

private async Task<string> GetJsonObjFromUrl(string urlRoutes)
{
    HttpClient c = new HttpClient(new NativeMessageHandler());

    var resp = await c.SendAsync(new HttpRequestMessage(HttpMethod.Get, new Uri(urlRoutes)));

    if (resp.IsSuccessStatusCode)
    {
        var json = await resp.Content.ReadAsStringAsync();

        return json;
    }

    return null;
}

What am I doing wrong?

Edit: Just putting this here because this was driving me crazy whole night. Ends up the caller way, way above forgot to put await. The execution continues straight after and never returns to get the result. That's why I never got any results... :\

Upvotes: 0

Views: 130

Answers (2)

Stephen Cleary
Stephen Cleary

Reputation: 456577

The code just don't go hit anywhere below client.SendAsync / GetStringAsync

I suspect that further up your call stack, your code is calling Result / Wait / GetAwaiter().GetResult() on a task. If called from a UI thread, this will deadlock, as I explain on my blog.

The deadlock is caused by the async method attempting to resume on the UI context, but the UI thread is blocked waiting for the task to complete. Since the async method must complete in order to complete its task, there's a deadlock.

The proper fix is to replace that Result / Wait with await.

Upvotes: 1

Archiman
Archiman

Reputation: 1080

In your PCL use:

HttpClient httpClient = new HttpClient();
var json = await httpClient.GetStringAsync(Url);

In case of using HTTPS. In Android, your main activity:

protected override void OnCreate(Bundle bundle)
{
    ServicePointManager.ServerCertificateValidationCallback +=(sender, cert, chain, sslPolicyErrors) => true;
}

In iOS, in your AppDelegate:

public override bool FinishedLaunching(UIApplication app, NSDictionary options)
{
    ServicePointManager.ServerCertificateValidationCallback += (sender, cert, chain, sslPolicyErrors) => true;

    return base.FinishedLaunching(app, options);
}

Upvotes: 0

Related Questions