Doubt over HTTP POST

3

I'm trying to send SMS through a WebService.

Sending a single SMS is simple. Just use the URL in this format:

https://xxxxx.com/sendMessage?messageText=mensagemdeteste&destination=552199998888&key=XXXX

However according to the WebService documentation I can send several at the same time with this URL format:

https://xxxxx.com/sendMessageBatch?messageText=mensagemdeteste&key=XXXX

It says that I should add the numbers in the HTTP POST BODY:

  

This option allows one message to be sent to more than one phone   number Destination numbers need to be in the body of the HTTP POST.

     

The body of the POST should be composed of lines containing the   destination phone numbers (line breaks only as separators):

destination1\n<destination2>\n<destination3>\n<destinationN>

But how does this work ?? I can move this body only via server, via C # for example ??

    
asked by anonymous 08.04.2015 / 20:17

2 answers

7

Yes, it is possible in C #. Your code would look like the following sample:

var destinos = "5555-5555\n5555-5556\n5555-9999"; //<-Números que receberão a msg

byte[] buffer= Encoding.ASCII.GetBytes(destinos);

var webReq = (HttpWebRequest) WebRequest.Create("https://xxxxx.com/sendMessageBatch?messageText=mensagemdeteste&key=XXXX");

webReq.Method = "POST";
// webReq.ContentType = "content-type"; <- caso necessário
webReq.ContentLength = buffer.Length;

var reqStream = webReq.GetRequestStream();
reqStream.Write(buffer, 0, buffer.Length);
reqStream.Close();

var webResp = (HttpWebResponse) webReq.GetResponse();

A similar code in jQuery:

$.ajax({
        url: 'https://xxxxx.com/sendMessageBatch?messageText=mensagemdeteste&key=XXXX',
        type: 'POST',
        data: '5555-5555\n5555-5556\n5555-9999',
        success: function(data, textStatus, xhr) {
                //Caso sua operação tenha sido bem-sucedida
            }
        }
    
08.04.2015 / 20:26
2

Since the release of C # 4.0, it is standard to use HttpClient (part of nuget Microsoft.Net.Http ) for orders web. This class creates a unified API to send / receive HttpRequestMessage s and HttpResponseMessage s.

string[] destinos = {"destino1", "destino2", "destino3"};
var destinosStr = string.Join(Environment.NewLine, destinos);

var content = new StringContent(destinosStr);
var client = new HttpClient();

var response = await client.PostAsync("https://xxxxx.com/sendMessageBatch?messageText=mensagemdeteste&key=XXXX", content);

The API is much clean and easy to use than the WebRequest API. No need to work with buffers and byte arrays, and supports asynchronous tasks.

    
09.04.2015 / 10:10