Consume web service from c #

1

I need to consume a web service from .NET; I have to connect to the following webservice:

Web service

EndPoint: / ext_ws / integration_school / update_debt_by_code

Method: POST

Params:

{api_key}: clave de autorización
{codigo}: código del estudiante
{valor_adeudado}: valor total adeudado
{valores_pendientes}: arreglo con el detalle de los valores pendientes de pago

Request Example:

{
 "api_key":  "############",
 "codigo":  "0885-E",
 "valor_adeudado": 120.65,
 "valores_pendientes":  [
  {
    "numero_factura" :  "001-001-0003875".
    "fecha" :  "01-02-2018",
    "monto_total" :  "120.65",
    "detalles" : [
      { "concepto" : "Pensión Enero", "valor" : "100.15" },
      { "concepto" : "Pensión Febrero", "valor" : "20.50" }
     ]
   }
 ]
}

Result: JSON structure:

result: (true, false) action result indicator

message: message of the action taken

Ahem. Result:

{
“resultado”: true,
“mensaje”: “Registro Actualizado Correctamente”
}

Looking for some information I have to consume it through the class HttpClient

I do not know if someone has an example of how he should do it or if there is some other more effective way to consume it?

    
asked by fsigu 02.03.2018 в 23:22
source

2 answers

1

I recommend doing it with Asynchronous Programming . You can avoid performance bottlenecks and improve the total response capacity of the application through asynchronous programming.

In the following example a communication is made with a ws (Web Service) for an object of the class "question". Although this method is done to return an object of this same class, modifying the content of "if (response.IsSuccessStatusCode)" can adjust it to your needs.

What I recommend is always work with objects in your ws and link it to project mediate the dll generated during the publication of your API.

Libraries:

using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Net.Http;
using System.Web.Http;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Web.Configuration;
using API.Model;
using System.Configuration;

Code:

    string url = ConfigurationManager.AppSettings["urlWS"] + "Pregunta/";


    public async Task<int> SavePregunta(Pregunta pregunta, bool isNewItem)
    {
        using (HttpClient client = new HttpClient())
        {
            try
            {
                var json = JsonConvert.SerializeObject(pregunta);
                var content = new StringContent(json, Encoding.UTF8, "application/json");
                var result = "";
                bool ok = false;
                HttpResponseMessage response = null;

                if (isNewItem)
                {
                    response = await client.PostAsync(url, content).ConfigureAwait(false);
                }
                else
                {
                    response = await client.PutAsync(url, content).ConfigureAwait(false);
                }

                if (response.IsSuccessStatusCode)
                {

                    result = await response.Content.ReadAsStringAsync();
                    pregunta = JsonConvert.DeserializeObject<Pregunta>(result);

                }

                return pregunta;

            }
            catch (Exception ex)
            {
                return 0;
            }
        }
    }

I hope it works for you. Regards!

    
answered by 23.08.2018 в 23:00
0

Although the question is very general I think it could help you as I see your communication will be using json (is a way to represent a class in text only) for this I recommend these libraries: link with this tool you can get a class from the "package" example link try to do something like this to generate the post:

public override bool Post(TModel model) //cambia el objeto para que sea tu clase
{
        try
        {
            HttpWebRequest request;
            Url = @"";//pones aqui la direccion web
            request = WebRequest.Create(Url) as HttpWebRequest;
            request.Timeout = 10 * 1000;
            request.Method = "POST";
            request.ContentType = "application/json; charset=utf-8";
            string json = JsonConvert.SerializeObject(model);
            using (var streamWriter = new StreamWriter(request.GetRequestStream()))
            {
                streamWriter.Write(json);
            }
            HttpWebResponse response = request.GetResponse() as HttpWebResponse;
            using (var streamReader = new StreamReader(response.GetResponseStream()))
            {
                string result = streamReader.ReadToEnd();
                return !string.IsNullOrEmpty(result);
            }

        }
        catch (Exception ex)
        {
            //si el post falla queda aqui
        }
        return false;
    }
    
answered by 03.03.2018 в 00:00