Send parameters to Restfull services

Asked

Viewed 1,557 times

0

I have a web application mvc and in it I have an action that should pass a parameter to a REST service. How do I pass a parameter to a REST service. I know that I will have to implement an Httppost, but how? Does anyone know a Tuto that can help us?

EDIT1

The following. Imagine a parent company with 7 stores. Each store with its team of sellers. A customer arrives at this store and makes a huge purchase. It is very common to sell more than R $ 5.000,00. In this sale there are several items. Well, let’s say a certain customer bought inputs, vaccines and so on and gave you 120,000. Since he has the money, he asks for a long term (until the harvest, maybe) a discount. It turns out that this discount is beyond the seller’s ability to grant, so he starts the guy right above him, who’s usually at the head office. How does he do it? Changing a flag in the BD(FLAG_LIBERACAO) from 1 to 0. This is when the system will act. This change the company developers will do (system done in Clarion/Interdev). What happens is, when the customer requests the discount, the seller clicks on a button that changes the Flag and already sends to the service (here my system enters) the Request (I put OK/Deny) but it can be anything. Then the service picks up this newly arrived information and fires a Push Notification(PN). And each manager/director receives and does what he has to do. There’s a rule for everyone to receive, but that’s something else and I’m already on it. I hope I’m clear, but if there’s any doubt, I’m here to answer.

EDIT2

I set up my API like this:

public class GetValueLiberacao
    {
        [Route("api/postvalueliberacao/{value}")]
        [AcceptVerbs("Post")]
        public HttpResponseMessage PostValueLiberacao([FromBody] string value)
        {
            try
            {
                if (value == "Ok")
                {
                    Task t = new Task(async () =>
                    {
                        await SenderMessage();
                    });
                    t.Start();
                }

                var response = new HttpResponseMessage(HttpStatusCode.Created)
                {
                    Content = new StringContent("OK")
                };

                return response;
            }
            catch(Exception ex)
            {
                var response = new HttpResponseMessage(HttpStatusCode.Created)
                {
                    Content = new StringContent("Falha \n" + ex.Message)
                };
                return response;
            }
        }

        public static async Task<IFCMResponse> SenderMessage()
        {
            FCMClient client = new FCMClient("AAAA0myCZjE:APA91bETPO0K3EtgBhHz_gMXDtBTiQrCsFaOW8wmFxbk5XvYhxTRIW9ZQR_mxNU8ThWe0d0A40JzG-Up_P2qyCw9hf6DrrRJfpynRIpnv_8FjIk3BsElnBuRenOi0h2r_h7Bv_"); //as derived from https://console.firebase.google.com/project/
            var message = new Message()
            {
                To = "APA91bGmgZnr2YMolubwS7c_e6AAkbVj6ga83lSHLo31FRUoom3iuS73PR1Bo6-iJEZWA88Xom7SWMrBK7edS6xVoe0kHdoIEowye4dsKXdtHdjd60_QEYcBkIi9QLyP7ZX6qdfdj", //topic example /topics/all
                Notification = new AndroidNotification()
                {
                    Body = "Solicitação de Novo Desconto",
                    Title = "Desconto",
                }
            };
            //CrossBadge.Current.SetBadge(1, "Teste");
            var result = await client.SendMessageAsync(message);
            return result;
        }
    }

In case I get OK in the parameter, I then trigger the Push Notification. Now I am working on the consumption and sending of the parameter, from another application. The question now would be the controller, as it would be, since it is for her that the program will send the data. I have not yet assembled. I just made this method and need to assemble the controller that will make all this happen. I will need to Enablecors?

EDIT3 I made my controller like this:

[RoutePrefix("api/postvalueliberacao")]
    public class GetLiberaItensController : ApiController
    {
        AutorizadorContext contexto = new AutorizadorContext();
        GetValueLiberacao libitens = new GetValueLiberacao();

        [Route("{value}")]
        [AcceptVerbs("Post")]
        public HttpResponseMessage GetLiberaItens(string value)
        {
            return libitens.PostValueLiberacao(value);
        }
    }

I’ll start filling out. First on Postman and then on my app.

  • you described what the application has to do...you want to actually is to create the api ? It is very wide and will certainly be closed... consume an api ? need her documentation, or at least know how it works...

  • It is not creating the API, but passing a parameter to a service. That’s it. I only developed my rule to make it clearer. I just want to know how I send a parameter, a string, a bool, anything to a REST.

  • so...you need to know how this api normally gets it in the url, but you can get it in header or content as well

  • Like this: http://meusite.com.br/autoriza/api/getparametro/{value}. As sending a desktop a parameter to get the value of my URL.

  • the api is yours ? show her code, route...controller...qlqr thing

  • I’m still doing and it’s one of the doubts when the subject is post, but I’m going to po this way: [Route("api/getliberaitens/{value}")]&#xA; [AcceptVerbs("Post")]&#xA; public string PostValueLiberacao([FromBody] string value)&#xA; {???????????????????&#xA; return value;&#xA; }

  • With the API above, running this on Postman, it should work?http://www.inetglobal.com.br/autorizador/api/postvalueliberacao/Ok

Show 3 more comments

1 answer

2

I use the following function:

    public static string HttpPost(string url, string postData, string token)
    {
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);

        byte[] data = Encoding.ASCII.GetBytes(postData);
        request.Headers["api-token"] = token;
        request.Method = "POST";
        request.Accept = "application/json";
        request.ContentType = "application/json; charset=utf-8";
        request.ContentLength = data.Length;

        using (var stream = request.GetRequestStream())
        {
            stream.Write(data, 0, data.Length);
        }

        var response = (HttpWebResponse)request.GetResponse();

        var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();

        return responseString;
    }

Just enter the url, the data that will be sent, in case it is to send a json, and the token that should go in the header. Remembering that this is specific to each api, and you have to refer to its documentation.

Edit:

considering the following code for the API:

    [ApplyModelValidation]
    public IHttpActionResult Post([FromBody]string valor)
    {
        try
        {
             //faz qualquer processo...               
             return Ok("retorno: "+ valor);
        }
        catch (Exception ex)
        {
            return InternalServerError(ex);
        }
    }

You would consume her like this:

POST METHOD:

    public static string HttpPost(string url, string postData)
    {
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);

        byte[] data = Encoding.ASCII.GetBytes(postData);
        request.Method = "POST";
        request.Accept = "text/plain";
        request.ContentType = "text/plain; charset=utf-8";
        request.ContentLength = data.Length;

        using (var stream = request.GetRequestStream())
        {
            stream.Write(data, 0, data.Length);
        }

        var response = (HttpWebResponse)request.GetResponse();

        var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();

        return responseString;
    }

Consuming:

public void Consumir()
{
    string retorno = HttPost("http://minhaapi.com.br/api/controller/","esse texto q eu estou enviando");

    //resultado: "retorno: esse texto q eu estou enviando";
}

I hope it helps, and obviously I haven’t tested, there may be some mistake.

  • What do I put in this token? I don’t understand the token. What I want is to send this: "OK" or "DENIED" to the service and depending on the answer, it sends a notification to the Android App. In the service has the PN sending code. I just need to make a code that takes the value of a flag in the bank and send one of these words to the service.

  • you asked how to do the POST for a service...you need to have the documentation of that service... the token in case, is why the service I use, is authorized by a token, if you do not have to send a token in the header, just remove

  • So this is a question of how to send a parameter. I will remove the token and see if I can send something. Soon to finish and as I advance, things will appear, Hehe.

  • understanding how parameter... would be in the url... you can also send by content, there goes in the body of the request... if you put how the api works facilitates the understanding

  • @pnet see if it helps

  • Rovann, I’m gonna test it, and the next day or so, post, because it’s 5:17 already. I stay until midnight, but in case we can’t talk anymore today, I put on until tomorrow. I’ll start doing and testing.

  • @pnet managed to solve ?

  • Dude, it’s giving an error that I don’t know if it’s from the provider or mine. I opened a call at redehost(provider) to find out. I’ll try on localhost now and see what happens.

Show 3 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.