Trying to get HttpClient to work on .Net


#1

I use the HttpClient on multiple platforms IOS, Android, Windows and want to use it to connect and download data via this service. this is how far I have got I change the username for my username and the apikey with the one sent in the email, I am getting authentication errors, also don’t know how to pass parameters like airport etc, I just need one working example to get me going.

thank you.

public async Task GetArrivals() {
var message = new HttpRequestMessage();
var content = new MultipartFormDataContent();
message.Method = HttpMethod.Post;
message.Content = content;
message.RequestUri = new Uri(“http://username:apikey@flightxml.flightaware.com/json/FlightXML2/Arrived”);
string result = “”;
try {
using (HttpClient client = new HttpClient()) {
var operation = client.SendAsync(message, HttpCompletionOption.ResponseHeadersRead);
result = await operation.Result.Content.ReadAsStringAsync();
return result.ToString();
}
} catch (Exception ex) {
if (ex.InnerException.Message.ToString().IndexOf(“ConnectFailure”, StringComparison.CurrentCultureIgnoreCase) > -1) {
return “”;
}
return null;
}
}


#2

You should be able to do something like this:


using System;
using System.Threading.Tasks;
using System.Net;
using System.Net.Http;

namespace ConsoleApplication1
{
    class Program
    {
        static var username = "xxxxxxxx";
        static var ApiKey = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxx";

        static async Task makeRequest()
        {
            var ApiBaseUrl = new Uri("https://flightxml.flightaware.com/json/FlightXML2/FlightInfoEx?ident=UAL6");

            var credentials = new NetworkCredential(username, ApiKey);
            var handler = new HttpClientHandler { PreAuthenticate = true, Credentials = credentials };

            var http = new HttpClient(handler);
            
            HttpResponseMessage response = await http.GetAsync(ApiBaseUrl);
            response.EnsureSuccessStatusCode();
            if (response.Content.Headers.ContentType.MediaType == "application/json")
            {
                var rawbody = await response.Content.ReadAsStringAsync();
                Console.Write("Got JSON body:");
                Console.Write(rawbody);
                
            }
            
        }

        static void Main(string] args)
        {
            makeRequest().Wait();
        }
    }
}



#3

Thanks very much for the reply, sorry for the delay in reading the post I did not get a notification of the post via email so I just by chance had a look and found the reply.

This works thanks, now I am using enroute and need to if possible work out the inbound terminal number as there is 5 in total in heathrow, if this is not possible is there a list somewhere I can pull down with flight information and what terminal that comes into?

thanks for your help.