The httpwebrequest control with call post and get in C# ✅


How to consume json .net?

The code to call the API is to make a GET request, we need to place the properties of the httpwebrequest object depending on what we need to develop, in this example what we are going to do is bring data from a "web service" api, through httpwebrequest post c # and httpwebrequest get c # what will do is cast a JArray to go through the object and bring a specific data from the node "company" to later assign it to a variable and save that data in a database of sql server.

How does the httpwebrequest work?

First of all we have to place the service route, it is important that the route is correct so that it does not have errors when doing the authentication, in this route of the service we will show them as add parameter that in this case is the user "username_ " to bring us your specific data of that user as shown in (Example 1.-), we have two examples in which we put the user's parameter in a different way (Example 2.-) it is assigned the parameter in the chain of the Json unlike the previous one that was passed in the service route this depends on the documentation of each service on how it should be consumed, in these two examples we will use the httpwebrequest contenttype with the property application / json since in the two examples we will consume a Json however we put the two examples.


                   Example 1.- 
                      
                          String cadena = "https://development.spyasociados.com/api/users/" + username_ + "/employment";
var httpWebRequest = (HttpWebRequest)WebRequest.Create(cadena);
httpWebRequest.ContentType = "application/json";

                    Example 2.- 
                    
                          String cadena = "https://development.spyasociados.com/api/users/executeAPIcall";
var httpWebRequest = (HttpWebRequest)WebRequest.Create(cadena);
httpWebRequest.ContentType = "application/json";
string jsonApi = "{'apiUsername':'corporativo'," + "'apiPassword':'asd333rrg5/$3'," + "'apicallsetinput':[{" + "'_apicall':'read'," + "'event_id':3234," + "'users':'" + username_ + "' " + "}]}";


We have two ways to consume the service, httpwebrequest add header or httpwebrequest credentials.

As we discussed earlier this depends on the consumption of the api of each service, we show you two ways in (Example 1.-) a header is added in which the Authorization node is used with the control httpWebRequest.Headers.Add (...) and it is placed a token with which the user is authenticated so that he can consume all the services through the control httpwebrequest get c #, this is done to have security and integrity in his consumption data making the call of the httpwebrequest control async. In (Example 2.-) a user and a password such as httpwebrequest authentication are placed as a parameter.


                    Example 1.- 
                      
                          httpWebRequest.Headers.Add("Authorization", "ClaveAccesoasdasdasdas2342352#?0");
                      
                    

                    Example 2.- 
                    
                            string jsonApi = "{'apiUsername':'corporativo', 'apiPassword':'asd333rrg5/$3'," + ....
                           
                      
                    



  • Audífonos Redmi Airdots
  • $510.00 Envío GRATIS. Ahorras: $320.00 (39%)
  • Hasta 4 horas de uso continuo. Audífonos Redmi Airdots Compatibles con Bluetooth 5.0



Type of method for the asynchronous call to the service either as httpwebrequest post c # or httpwebrequest get c #.

The call or consumption of the service information can be done in two ways (power-on self-test, call the service "behind" or "after") OR get (send the data using the url) depending on how the service requires it, we show you the examples:


                    Example 1.- 
                      
                          httpWebRequest.Method = "GET";
                      
                    

                    Example 2.- 
                    
                            httpWebRequest.Method = "POST";
                           
                      
                    

How to extract data from the Json string with the httpWebRequest control? GetRequestStream ()?


Here's how to use the httpWebRequest.GetRequestStream () control to extract data from the Json string and convert the text string from a Json to a JArray, in (Example 1.-) it is used The StreamReader control will only be used to read the service, authenticating with the requerod token with the httwebrequest credentials control, and parse a JArray to cast the input string to JArray, then the object is traversed with a foreach entering its Json properties and the "company" node is found to extract the required data as shown in the example unlike (Example 2.-) In this we use the control StreamWriter since we write in the service placing the user, password and event type doing the post since this is the way you authenticate yourself and pass the user whose data you need, later with the JsonConvert object. DeserializeObject (number); we enter the Json without casting it as it returns a pure Json and in this way we bring your data as shown in the example.


                    Example 1.- 
                      
                          var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
                            using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
                            {
                                //Extraer datos de la cadena Json 
                                var result = streamReader.ReadToEnd();
                                //Convertir la cadena de texto de un Json a n JArray
                                JArray jsonPreservar = JArray.Parse(result);
                                foreach (JObject jsonOperaciones in jsonPreservar.Children())
                                {
                                    //Aqui para poder identificar las propiedades y sus valores
                                    foreach (JProperty jsonOPropiedades in jsonOperaciones.Properties())
                                    {
                                        //Debes recorrer el arreglo completo, asi puedes obtener todos los valores de las propiedades
                                        string propiedad = jsonOPropiedades.Name;
                                        //Leer Json y sacar valor de un campo
                                        if (propiedad.Equals("empresa"))
                                        {
                                            //Recorrer Json tomando parte de los valores
                                            var val = Convert.ToString(jsonOPropiedades.Value);
                                            dynamic jsonObj = JsonConvert.DeserializeObject(val);
                                            String Distribuidor = Convert.ToString(jsonObj["Id"].ToString());
                                            return Distribuidor;
                                        }
                                    }
                                }

                                JObject data = JObject.Parse(jsonPreservar[0].ToString());
                                var id = Convert.ToInt32(data["id"]);
                                return "";
                            }
                      
                    

                      Example 2.- 
                      
                        using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
                          {
                              string jsonApi = "{'apiUsername':'corporativo'," +
                              "'apiPassword':'asd333rrg5/$3'," +
                              "'apicallsetinput':[{" +
                              "'_apicall':'read'," +
                              "'event_id':3234," +
                              "'users':'" + username_ + "' " +
                              "}]}";

                              streamWriter.Write(jsonApi);
                              streamWriter.Flush();
                              streamWriter.Close();
                          }

                          var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
                          using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
                          {
                              var result = streamReader.ReadToEnd();
                              dynamic jsonObj = JsonConvert.DeserializeObject(result);
                              var numero = jsonObj["apicallsetoutput"][0].ToString();
                              dynamic jsonObj_ = JsonConvert.DeserializeObject(numero);
                              _apicallresultcode = Convert.ToInt16(jsonObj_["_apicallresultcode"].ToString());

                              if (_apicallresultcode == 1)
                              {
                                  _id = Convert.ToInt32(jsonObj_["id"].ToString());
                              }
                          }
                             
                        
                      

To finish we leave you all the code of the httpwebrequest post c # with all the parameters.

Here we place the complete code of c of the two examples so that you apply the one that best suits your system development, in conclusion we can see in these two examples of the httpwebrequest in c # that in (Example 1.-) it is used the object httpwebrequest authorization header bearer to be able to access the service unlike the (Example 2.-) user and password are used to not use the Headers, another difference is that in the (Example 1.-) the cast is made to the object JArray.Parse (result); to be able to travel the Json, without further ado I leave you to observe the code, I hope you serve these examples.


                      Example 1.- 
                      
                          
                        private String extraerDatosJsonR(String username_)
                         {
                            String cadena = "https://development.forwardcompany.com/api/users/" + username_ + "/employment";

                            var httpWebRequest = (HttpWebRequest)WebRequest.Create(cadena);
                            httpWebRequest.ContentType = "application/json";
                            httpWebRequest.Method = "GET";
                            httpWebRequest.Headers.Add("Authorization", "ClaveAccesoasdasdasdas2342352#?0");
                            try
                            {
                                var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
                                using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
                                {
                                    //Extraer datos de la cadena Json 
                                    var result = streamReader.ReadToEnd();
                                    //Convertir la cadena de texto de un Json a n JArray
                                    JArray jsonPreservar = JArray.Parse(result);
                                    foreach (JObject jsonOperaciones in jsonPreservar.Children())
                                    {
                                        //Aqui para poder identificar las propiedades y sus valores
                                        foreach (JProperty jsonOPropiedades in jsonOperaciones.Properties())
                                        {
                                            //Debes recorrer el arreglo completo, asi puedes obtener todos los valores las propiedades
                                            string propiedad = jsonOPropiedades.Name;
                                            //Leer Json y sacar valor de un campo
                                            if (propiedad.Equals("empresa"))
                                            {
                                                //Recorrer Json tomando parte de los valores
                                                var val = Convert.ToString(jsonOPropiedades.Value);
                                                dynamic jsonObj = JsonConvert.DeserializeObject(val);
                                                String Empresa = Convert.ToString(jsonObj["Id"].ToString());
                                                return Empresa;
                                            }
                                        }
                                    }
                                    JObject data = JObject.Parse(jsonPreservar[0].ToString());
                                    var id = Convert.ToInt32(data["id"]);
                                    return "";
                                }
                            }
                            catch (WebException ex)
                            {
                                //Log de errores.
                                String error = ex.Message;
                                return "";
                            }

                        }
                          
                      
                    

                    Example 2.- 
                       
                         private Int64 existeUsuario(String username_ , String Perfil)
                          {
                                  String cadena = "https://development.spyasociados.com/api/users/executeAPIcall";

                                   var httpWebRequest = (HttpWebRequest)WebRequest.Create(cadena);
                                  httpWebRequest.ContentType = "application/json";
                                  httpWebRequest.Method = "POST";
                                  Int16 _apicallresultcode = 0;
                                  String entitlement_group = "";
                                  Boolean mismoPerfil = false;
                                  Int64 id = 0;
                                  using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
                                  {
                                      string jsonApi = "{'apiUsername':'corporativo'," +
                                      "'apiPassword':'asd333rrg5/$3'," +
                                      "'apicallsetinput':[{" +
                                      "'_apicall':'read'," +
                                      "'event_id':3234," +
                                      "'users':'" + username_ + "' " +
                                      "}]}";

                                      streamWriter.Write(jsonApi);
                                      streamWriter.Flush();
                                      streamWriter.Close();
                                  }

                                  var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
                                  using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
                                  {
                                      var result = streamReader.ReadToEnd();
                                      dynamic jsonObj = JsonConvert.DeserializeObject(result);
                                      var numero = jsonObj["apicallsetoutput"][0].ToString();
                                      dynamic jsonObj_ = JsonConvert.DeserializeObject(numero);
                                      _apicallresultcode = Convert.ToInt16(jsonObj_["_apicallresultcode"].ToString());

                                      if (_apicallresultcode == 1)
                                      {
                                          _id = Convert.ToInt32(jsonObj_["id"].ToString());
                                          //PERFIL ACTUAL DE LA API 
                                          try
                                          {
                                              dynamic events = jsonObj_.events["1415"];
                                              entitlement_group = events.entitlementgroup_name;
                                          }catch(Exception ex){}
                                          //PERFIL ACTUAL DE T.NET
                                          
                                          //HttpContext.Current.Session["entitlement_group"] = Perfil.ToString().Trim();
                                          entitlement_groupActual = Perfil.ToString().Trim();
                                          //COMPARAMOS PERFILES SI ES DIFERETTEN DEBEMOS DE ACTUALIZARLO EN EL API
                                          try
                                          {
                                              if (Perfil.ToString().Trim() == entitlement_group.ToString().Trim())
                                                  mismoPerfil = true;
                                              else
                                              {
                                                  String pp = jsonObj_["id"];
                                                  id = Convert.ToInt64(pp);
                                              }
                                          }
                                          catch (Exception ex) {

                                              String pp = jsonObj_["id"];
                                              id = Convert.ToInt64(pp);
                                          
                                          }
                                      }
                         
                                  }
                                  if (_apicallresultcode == 0)
                                      return 2;//NO existe

                                  if (_apicallresultcode == 1 & mismoPerfil == true)
                                      return 1;//Si existe y tiene el mismo perfil
                                  else
                                  {
                                      return id;//Si existe pero tiene diferente perfil, se tiene que eliminar el registro y dar de alta con el nuevo perfil.
                                  }
                              }
                           
                      
                      


Nombre Comentarios
{{ ds.fcNombre_ }} {{ ds.fcComentarios_ }}


Write your comments on this article I hope you have served the explanation of these objects: httpwebrequest post c # and httpwebrequest get c#.


{{ blog.bio }}

{{ blog.comentario }}

FIRST NAME *
EMAIL
COMMENTS *

The personal data collected by spyasociados.com, through its different points of reception, will be protected and treated based on the provisions of the Federal Law on Protection of Personal Data held by individuals.