How to execute a URL passing C #

0

Hello,

I'm doing for study purposes, a way to fetch and bring vehicle information from the api's direct fipe table ( link ) . What I can not do at first is to execute the URL passing parameters. For example:

I need to request the list of vehicle brands according to type, passing the type of vehicle (car, motorcycle or truck). I made a combobox with these options to be chosen by the user and stored in a variable of type 'Object'.

Object tipoSelecionado = cmbTipo.SelectedItem;

Now what I do not know is the url: link pass in the field [type] the variable ' tipoSelecionado ' and store the result in Json in the array ' Marcas '.

public class Marcas
        {
            public string key { get; set; }
            public string name { get; set; }
            public string id { get; set; }
            public string fipe_name { get; set; }
        }

Thank you in advance.

    
asked by anonymous 12.04.2016 / 22:09

1 answer

0

You can use the WebClient () for this. This would be an example:

 using (var client = new WebClient())
            {   
                //url de destino. Aqui você pode colocar os parâmetros que desejar
                var url = "http://fipeapi.appspot.com/api/1/carros/veiculos/21.json"; 
                //Download do resultado
                var json = client.DownloadString(url);
                var serializer = new JavaScriptSerializer();
                //Descerialização em uma lista dinâmica. Pode adequar sua classe, se rpeferir
                var model = serializer.Deserialize<dynamic>(json);

            }

In this example, your variable model will already have all the elements that will be returned.

In this answer I have an example of how to implement using Asp.NET MVC.

If you are using WinForms, just do it this way:

Object selectedItem = comboBox1.get_SelectedItem();
using (var client = new WebClient())
                {   
                    //url de destino. Aqui você pode colocar os parâmetros que desejar
                    var url = "http://fipeapi.appspot.com/api/1/" + selectedItem.ToString() + "/veiculos/21.json"; 
                    //Download do resultado
                    var json = client.DownloadString(url);
                    var serializer = new JavaScriptSerializer();
                    //Descerialização em uma lista dinâmica. Pode adequar sua classe, se rpeferir
                    var model = serializer.Deserialize<dynamic>(json);

                }

This way you will concatenate the values in the url.

    
12.04.2016 / 22:35