API login

Obaid Khan7 years ago

Actually I want to make a windows 10 application for windows store. I will share it on github too. Your cooperation will he very helpful.

Obaid Khan7 years ago

I am using swagger generated library and there seems to be no option available for basic auth.

Primtek7 years ago

yes.. there is no token..
I use codes below to get a device info..
hope you can improve it for your requirement

    string url = "http://gps.mydomain.com:8082/api/devices?uniqueId=mydeviceId";

    var pairs = new List<KeyValuePair<string, string>> { };

    var byteArray = Encoding.ASCII.GetBytes("your_ID"+ ":" + "your_Password");

    var client = new HttpClient();
    client.DefaultRequestHeaders.TryAddWithoutValidation("Content-Type", "application/json");
    client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray));
    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

    var content = new FormUrlEncodedContent(pairs);

    var response = client.GetAsync(url).Result;
    HttpStatusCode statusCode = response.StatusCode;

    switch (statusCode)
    {
        case HttpStatusCode.OK:
            {
                response.EnsureSuccessStatusCode();
                string res = response.Content.ReadAsStringAsync().Result;
                if (response.IsSuccessStatusCode)
                {
                    JArray rows = JArray.Parse(res);
                    if (rows.HasValues)
                    {
                        foreach (JToken row in rows)
                        {
                            id = (int)row["id"];
                            positionId = (int)row["positionId"];
                            status = (string)row["status"];
                            groupId = (int)row["groupId"];
                        }
                    }
                }
            }
            break;

   ..
   ..
   ..
    }

}
Obaid Khan7 years ago

Thank you for sharing your code. I have managed to use the swagger library and implemented a gui interface with GMaps. Im getting the problem of fetching past positions of the devices.

Obaid Khan7 years ago

I have very little experience with http. Can you please show me how to add parameters to httpclient class on c#. Example code would be really appreciated. Thank you

Primtek7 years ago

I use code below to get list of device positions..
to get its current position just add "&id=" at the end of the query string and pass positionid value..
hopefully someone here can improve it.. :)

                string url = "http://gps.mydomain.com:8082/api/positions?deviceId=MYUNIQUEID&from=STARTDATE&to=ENDDATE";

                var pairs = new List<KeyValuePair<string, string>> { };

                var byteArray = Encoding.ASCII.GetBytes(GPSAccount_Id + ":" + GPSAccount_Password);

                var client = new HttpClient();
                client.DefaultRequestHeaders.TryAddWithoutValidation("Content-Type", "application/json");
                client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray));
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

                var content = new FormUrlEncodedContent(pairs);
                var response = client.GetAsync(url).Result;
                HttpStatusCode statusCode = response.StatusCode;

                switch (statusCode)
                {
                    case HttpStatusCode.OK:
                        {
                            response.EnsureSuccessStatusCode();
                            string res = response.Content.ReadAsStringAsync().Result;
                            string status = string.Empty;
                            string message = string.Empty;
                            if (response.IsSuccessStatusCode)
                            {
                                JArray rows = JArray.Parse(res);
                                if (rows.HasValues)
                                {
                                    try
                                    {
                                        foreach (JToken row in rows)
                                        {
                                            try
                                            {
                                                int id = (int)row["id"];

                                                if (firstId == 0)
                                                { firstId = id; }

                                                lastId = id;

                                                string deviceid = (string)row["deviceid"];
                                                string type = (string)row["type"];
                                                string servertime = (string)row["serverTime"];
                                                string devicetime = (string)row["deviceTime"];
                                                string fixedtime = (string)row["fixTime"];
                                                bool outdated = (bool)row["outdated"];
                                                bool valid = (bool)row["valid"];
                                                lat = (double)row["latitude"];
                                                lng = (double)row["longitude"];
                                                double alt = (double)row["altitude"];
                                                double speed = (double)row["speed"];
                                                double course = (double)row["course"];
                                                address = (string)row["address"];
                                                double accuracy = (double)row["accuracy"];
                                                string network = (string)row["network"];

                                                JObject objAttr = (JObject)row["attributes"];
                                                if (objAttr.HasValues)
                                                {
                                                    if (objAttr.ContainsKey("alarm"))
                                                    { string alarm = (string)objAttr["alarm"]; }

                                                    distance = (double)objAttr["distance"];
                                                    double totaldistance = (double)objAttr["totalDistance"];

                                                    bool motion = (bool)objAttr["motion"];
                                                }
                                            }
                                            catch { }
                                            finally { }
                                        }
                                    }
                                    catch { }
                                    finally { }
                                    ret = true;
                                }
                            }
                        }
Primtek7 years ago

and dont forget to use ISO8601 format for 'from' and 'to'

Obaid Khan7 years ago

Thank you. I will test the code.

Obaid Khan7 years ago

Finally there is something that works. Thank you primtek for sharing your code.
I get syntax error at

if (objAttr.ContainsKey("alarm"))

"JObject does not contain a definition for ContainsKey"

Primtek7 years ago

Hi..
make sure you use Newtonsoft.Json 11.0.0.0 or later

https://www.newtonsoft.com/json/help/html/T_Newtonsoft_Json_Linq_JObject.htm

AmitJangir3 years ago
                      string url = "http://demo3.traccar.org/api/session";

        var pairs = new List<KeyValuePair<string, string>>
            {
                new KeyValuePair<string, string>("email", "xyz@gmail.com"),
                new KeyValuePair<string, string>("password", "*****")
            };

        var client = new HttpClient();
        client.DefaultRequestHeaders.TryAddWithoutValidation("Content-Type", "x-www-form-urlencoded");

        var content = new FormUrlEncodedContent(pairs);
        var response = client.PostAsync(url, content).Result;
        HttpStatusCode statusCode = response.StatusCode;
        if (statusCode== HttpStatusCode.OK)
        {
            try
            {
                response.EnsureSuccessStatusCode();
                string res = response.Content.ReadAsStringAsync().Result;
                HttpHeaders header = response.Headers;
                if (response.IsSuccessStatusCode)
                {
                    JObject objGPS = JObject.Parse(res);
                    if (objGPS.HasValues)
                    {
                        var User_Id = (int)objGPS["id"];
                        IEnumerable<string> headerValues = response.Headers.GetValues("set-cookie");
                        var User_Token = headerValues.FirstOrDefault();
                    }
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }


        }

to fetch token manually, let me know if i am wrong thank you!