GET and POST to a webservice on ASP.net (c#)

Thank you Pylon
Hi Pylon you couldn't be more accurate on your recomendation to learn xml and http, I'm on that path too, the only fact is that I cannot wait to finish my training since I must finish this "project" for one subject in order to get my bachelor degree, therefore I'm doing all the learning at the same time... hopelly I find you on my path and you was really helpful, I tested your code but I get this output on the serial monitor:

connecting...
connected
H
disconnecting.

I presume that it is because of this code segment

void loop()
{
  // if there are incoming bytes available 
  // from the server, read them and print them:
  if (client.available()) {
    char c= client.read();
    Serial.print(c);
   }

But this is the SAME code I used to obtain the serial output that I mentioned on my first question.. so what did I scewed now? hope you can guide me here

Try changing that "if" to a "while" to read all available characters before checking for a closed connection. That's because your connection may already be closed but you still have bytes in your input buffer (on the Ethernet Shield).

ITS ALIVE the beast is ALIVE lol

I can connect to the webservice and receive this
connecting...
connection failed

disconnecting.
connecting...
connected
HTTP/1.1 200 OK
Cache-Control: private, max-age=0
Content-Type: text/xml; charset=utf-8
Server: Microsoft-IIS/8.5
X-AspNet-Version: 4.0.30319
X-Powered-By: ASP.NET
Date: Tue, 22 Apr 2014 18:01:17 GMT
Connection: close
Content-Length: 402

<?xml version="1.0" encoding="utf-8"?>2014-04-22T15:01:17.4665176-03:00

disconnecting.

but as you can see the first attempt fail and I need to reset the card, any clues on that?

Post your sketch. That output is not from the sketch you posted.

yes it is... here is the full sketch

/*
  Web client
 
 */

#include <SPI.h>
#include <Ethernet.h>

// Enter a MAC address for your controller below.
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
// if you don't want to use DNS (and reduce your sketch size)
// use the numeric IP instead of the name for the server:
IPAddress server(192,168,2,90);  // numeric IP (no DNS)
//char server[] = "http://toponet.zapto.org:90";    // using DNS

// Set the static IP address to use if the DHCP fails to assign
IPAddress ip(192,168,2,105);

// Initialize the Ethernet client library
// with the IP address and port of the server 
// that you want to connect to (port 80 is default for HTTP):
EthernetClient client;

void setup() {
 // Open serial communications and wait for port to open:
  Serial.begin(9600);
   while (!Serial) {
    ;
  }
  if (Ethernet.begin(mac) == 0) {
    Serial.println("Failed to configure Ethernet using DHCP");
    Ethernet.begin(mac, ip);
  }
  delay(1000);
  Serial.println("connecting...");
  if (client.connect(server, 80)) {
    Serial.println(F("connected"));
    // Make a HTTP request:
    /*
    POST /WebServiceSQL/WebServiceSQL.asmx HTTP/1.1
    Host: toponet.zapto.org
    Content-Type: application/soap+xml; charset=utf-8
    Content-Length: length
    
    <?xml version="1.0" encoding="utf-8"?>
    <soap12:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap12="http://www.w3.org/2003/05/soap-envelope">
    <soap12:Body>
    <logactivation xmlns="http://toponet.zapto.org">
    <pinnumber>int</pinnumber>
    </logactivation>
    </soap12:Body>
    </soap12:Envelope>
    */
    client.println(F("POST /WebServiceSQL/WebServiceSQL.asmx HTTP/1.1"));
    client.println(F("Host: 192.168.2.90"));
    client.println(F("Content-Type: text/xml; charset=utf-8"));
    client.println(F("Content-Length: 350"));
    client.println(F("Connection: close"));
    client.println(F("SOAPAction: \"http://toponet.zapto.org/logactivation\""));
    client.println();
    client.println(F("<?xml version=\"1.0\" encoding=\"utf-8\"?>"));
    client.println(F("<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">"));
    client.println(F("<soap:Body>"));
    client.println(F("<logactivation xmlns=\"http://toponet.zapto.org\">"));
    client.println(F("<pinnumber>3</pinnumber>"));
    client.println(F("</logactivation>"));
    client.println(F("</soap:Body>"));
    client.println(F("</soap:Envelope>"));
  } 
  else {
    // kf you didn't get a connection to the server:
    Serial.println("connection failed");
  }
}

void loop()
{
  // if there are incoming bytes available 
  // from the server, read them and print them:
  if (client.available()) {
    char c= client.read();
    Serial.print(c);
   }

  // if the server's disconnected, stop the client:
  while (!client.connected()) {
    Serial.println();
    Serial.println("disconnecting.");
    client.stop();

    // do nothing forevermore:
    while(true);
  }
}

yes it is... here is the full sketch

No, it isn't because this sketch would stay in an endless loop after disconnecting and not connect again. Did you press the reset button in between? If yes, this would have been a quite important information.
If this was the reason, you might have to check what's going on in your network. I use the WireShark tool (Wireshark download | SourceForge.net) to sniff the traffic but I don't know if you already know enough about networks to use such a tool.

but as you can see the first attempt fail and I need to reset the card, any clues on that?

I think that I explained that there... yes I have to press the reset button in the middle... may be my english was not good enough to express my thoughts lol

so basically and wrapping up the first time I run this, I got a connection fail, and then I push the reset button, and then it works perfect

only because you helped me

Client test code you can try several times.

//zoomkat 9-22-12
//simple client test
//for use with IDE 1.0.1
//with DNS, DHCP, and Host
//open serial monitor and send an e to test
//for use with W5100 based ethernet shields
//remove SD card if inserted

#include <SPI.h>
#include <Ethernet.h>

byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED }; //physical mac address

char serverName[] = "web.comporium.net"; // zoomkat's test web page server
EthernetClient client;

//////////////////////

void setup(){

  if (Ethernet.begin(mac) == 0) {
    Serial.println("Failed to configure Ethernet using DHCP");
    // no point in carrying on, so do nothing forevermore:
    while(true);
  }

  Serial.begin(9600); 
  Serial.println("Better client test 9/22/12"); // so I can keep track of what is loaded
  Serial.println("Send an e in serial monitor to test"); // what to do to test
}

void loop(){
  // check for serial input
  if (Serial.available() > 0) //if something in serial buffer
  {
    byte inChar; // sets inChar as a byte
    inChar = Serial.read(); //gets byte from buffer
    if(inChar == 'e') // checks to see byte is an e
    {
      sendGET(); // call sendGET function below when byte is an e
    }
  }  
} 

//////////////////////////

void sendGET() //client function to send/receive GET request data.
{
  if (client.connect(serverName, 80)) {  //starts client connection, checks for connection
    Serial.println("connected");
    client.println("GET /~shb/arduino.txt HTTP/1.1"); //download text
    client.println("Host: web.comporium.net");
    client.println("Connection: close");  //close 1.1 persistent connection  
    client.println(); //end of get request
  } 
  else {
    Serial.println("connection failed"); //error message if no client connect
    Serial.println();
  }

  while(client.connected() && !client.available()) delay(1); //waits for data
  while (client.connected() || client.available()) { //connected or data available
    char c = client.read(); //gets byte from ethernet buffer
    Serial.print(c); //prints byte to serial monitor 
  }

  Serial.println();
  Serial.println("disconnecting.");
  Serial.println("==================");
  Serial.println();
  client.stop(); //stop client

}

Hi zoomkat thanks for helpin g here too..

I'm usign a webservice that returns the date form ethernet, so I want to parse the client.read() so I can check for an specific day, month, year and hours/minutes, therefore I-m wondering if you can help me on how to customize the Inchar line to look for this items.. do you have an approach here.? many thanks!

You might check textfinder.

http://playground.arduino.cc/Code/TextFinder

I think that I explained that there... yes I have to press the reset button in the middle... may be my english was not good enough to express my thoughts lol

Excuse me, I misinterpreted you final comment. What do you do before the first run? Power up the Arduino? Upload the sketch? How much time is between "Connecting..." and "Connection failed"? Do you have full control over the server the Arduino is connecting to?

Hi Pylon.

sorry for the dealy, basically I plug this in and wait for 5 seconds, there is the connection failed message and then I click the reset button and then it work perfectly.

I want to ask on this post also the best way to capture all the webservice information into a string ( one string, instead of reading char by char) so I can then perform a seach on that to look at the result, unless you can tell me that on arduino I can ask for the result of the webservice and store that in a variable... like c# I mean something like

result=servive.webservice(1);
where I can get on result the date and time....

thanks again for your help

I want to ask on this post also the best way to capture all the webservice information into a string ( one string, instead of reading char by char) so I can then perform a seach on that to look at the result, unless you can tell me that on arduino I can ask for the result of the webservice and store that in a variable... like c# I mean something like

The Arduino is not a perfect partner for a webservice because webservices usually are designed for computers with lots of resources like todays PCs and servers. The Arduino (at least all equipped with an ATmega328) have 2kB of RAM, many results of webservices are bigger than that. You haven't enough memory to store the complete result and search in it afterwards, so you have to parse the result while it's coming in and get all necessary information out.

What do you want to achieve? What's the content of the webservice call you're trying to implement?

basically I plug this in and wait for 5 seconds, there is the connection failed message and then I click the reset button and then it work perfectly.

I never saw such a behavior in my sketches. Is it possible that any device in your network isn't able to handle packets from the Arduino just a few moments after it's link got up? What happens if you extend the delay() call in your setup() routine to let's say 10 seconds?

HI it's me again... well I'm really screwed I cannot make this work... If i run this requests it works fine the first 3 or 4 times but then it crashed sending a LOT of code...

here is the code on arduino

#include <SPI.h>
#include <Ethernet.h>

byte mac[] = {0xEE, 0xDD, 0xBE, 0xEF, 0xFE, 0xED }; // DIRECCION MAC
IPAddress ip(192,168,2,91);  //DIRECCION IP PARA ARDUINO
EthernetServer server(80); //MODO Servidor y Puerto de trabajo
String readString=""; 
int pin=-1;
int state=-1;

void setup() 
{  
  for (int setoutpin = 6; setoutpin<=9; setoutpin++)//defino las salidas 6,7,8,9 como OUT y las pongo en HIGH
  {
    pinMode(setoutpin,OUTPUT);
    digitalWrite(setoutpin,HIGH);
  }
  Serial.begin(9600);//Monitorizacion via serie
  while (!Serial)
  {
    ;
  }//Espera a que se inicie
  Serial.println("Starting network...");
  Ethernet.begin(mac, ip);//Iniciando Ethernet
  Serial.print("My IP address is: ");  
  Serial.println(Ethernet.localIP());
  Serial.println("Waiting for new connections...");
  delay(500);
}
  
//VOID LOOP===================================================================
  
  void loop()
  {
    EthernetClient client = server.available();
    if (client) 
    {
      char data;
      readString="";      
      Serial.println("------------------------------------------------------");
      Serial.println("Connection detected");
      while ( client.available())
      {
        //delay(5);
        data = client.read();
        readString += data;
      }
      
      Serial.println("");
      Serial.println("The client sent: ");
      Serial.println(readString);
      Serial.println("");
      //delay(5); 
      
      if (data=='\n')
      {   
        client.println("HTTP/1.1 200 OK");
        client.println("Content-Type: text/html");
        client.println("Connection: close");
        client.println(); 
        client.println("");   
        
        Serial.println("HTTP/1.1 200 OK");
        Serial.println("Content-Type: text/html");
        Serial.println("Connection: close");
        Serial.println(); 
        Serial.println("");      

        if( readString.indexOf("?p=1")>=0)
        {
          Serial.print("Received pinnumber: 1 ");
          Serial.println("mapping to output: 6");
          pin=6;
        }
        
        if( readString.indexOf("?p=2")>=0)
        {
          Serial.print("Received pinnumber: 2 ");
          Serial.println("mapping to output: 7");
          pin=7;
        }
        
        if( readString.indexOf("?p=3")>=0)
        {
          Serial.print("Received pinnumber: 3 ");
          Serial.println("mapping to output: 8");
          pin=8;
        }  
        
          if( readString.indexOf("?p=4")>=0)
        {
          Serial.print("Received pinnumber: 4 ");
          Serial.println("mapping to output: 9");
          pin=9;
        }   
        
        if( readString.indexOf("&s=0")>=0)
        {
          Serial.println("Received state: 0");
          state=0;
        }
        
        if( readString.indexOf("&s=1")>=0)
        {
          Serial.println("Received state: 1");
          state=1;
        }
        
        if (state==0)
        {
            digitalWrite(pin,HIGH);
            Serial.print("Setting output: " );
            Serial.print(pin);
            Serial.println(" to state: OFF");  
            client.println("ARDUINO_OK");  
            Serial.println("ARDUINO_OK");  
        }
        
        if (state==1)
        {
            digitalWrite(pin,LOW);
            Serial.print("Setting output: " );
            Serial.print(pin);
            Serial.println(" to state: ON");
            client.println("ARDUINO_OK");
            Serial.println("ARDUINO_OK");  
        }
        
        if( readString.indexOf("?QueryDigital")>=0)
        {
          client.print("QUERY_OK");
          Serial.print("QUERY_OK");  
          for (int querypin = 6; querypin <= 9; querypin++) 
          {
            int sendpin = digitalRead(querypin);
            client.print(querypin);
            client.print("=");
            if (sendpin >0)
            {
              client.print("ON");
            }
            else
            {
              client.print("OFF"); 
            }
            client.print(",");            
          }
        }
        
        if (readString.indexOf("?efect1")>=0) //APAGO TODAS
        {
          client.print("EFECTO1_OK");
          Serial.print("EFECTO1_OK");
          for (int efectpin = 6; efectpin <= 9; efectpin++) 
          {
            digitalWrite(efectpin,HIGH);           
          }
        }
        
        if (readString.indexOf("?efect2")>=0) //ENCIENDO TODAS
        {
          client.print("EFECTO2_OK");
          Serial.print("EFECTO2_OK");
          for (int efectpin = 6; efectpin <= 9; efectpin++) 
          {
            digitalWrite(efectpin,LOW);           
          }
        }
        if (readString.indexOf("?efect3")>=0) //1,2,3,4
        {
          client.print("EFECTO3_OK");
          Serial.print("EFECTO3_OK");
          for (int efectpin = 6; efectpin <= 9; efectpin++) 
          {
            digitalWrite(efectpin,HIGH); //apago todas         
          }
          for (int efectpin = 6; efectpin <= 9; efectpin++) 
          {
            digitalWrite(efectpin,LOW);
            delay(1000);         
          }         
        }
        if (readString.indexOf("?efect4")>=0) //4,3,2,1
        {
          client.print("EFECTO4_OK");
          Serial.print("EFECTO4_OK");
          for (int efectpin = 6; efectpin <= 9; efectpin++) 
          {
            digitalWrite(efectpin,HIGH); //apago todas         
          }
          for (int efectpin = 9; efectpin >=6; efectpin--) 
          {
            digitalWrite(efectpin,LOW);
            delay(1000);         
          }         
        }
        if (readString.indexOf("?efect5")>=0) //4,1,3,2
        {
          client.print("EFECTO5_OK");
          Serial.print("EFECTO5_OK");
          for (int efectpin = 6; efectpin <= 9; efectpin++) 
          {
            digitalWrite(efectpin,HIGH); //apago todas         
          }
            digitalWrite(6,LOW);
            digitalWrite(9,LOW);
            delay(1000);
            digitalWrite(7,LOW);
            digitalWrite(8,LOW);
        }        
        if (readString.indexOf("?efect6")>=0) //3,2,4,1
        {
          client.print("EFECTO6_OK");
          Serial.print("EFECTO6_OK");
          for (int efectpin = 6; efectpin <= 9; efectpin++) 
          {
            digitalWrite(efectpin,HIGH); //apago todas         
          }
            digitalWrite(7,LOW);
            digitalWrite(8,LOW);
            delay(1000);
            digitalWrite(6,LOW);
            digitalWrite(9,LOW);
        } 
          delay(1);
          Serial.println("Client.stop");    
          Serial.println("");  
          Serial.println("Conection end");
          Serial.println("");
          Serial.println("waiting for new connections...");    
          client.stop();
        }
      }
    }

so basically I run this... sequence..

send 192.168.2.91/?QueryDigital
receive QUERY_OK6=ON,7=ON,8=ON,9=ON,
send http://192.168.2.91/?efect1

receive

K DUINO_OK 0 OK Content-Type: text/html Connection: close ARDUINO_OK QUERY_OK6=OFF,7=ON,8=ON,9=OHTTP/1.1 200 OK ConHTTP/1.1 200 OK Content-Type: text/html Connection: close ARDUINO_OK EFECTO5_OK 200 OK Content-Type: text/html Connection: close ARDUINO_OK EFECTO3_OKent-Type: text/html Connection: closeHTTP/HTTP/1.1 200 OK Content-Type: text/html Connnection: close Jack's Arudino Control Jack's LED OffOn on: close Jack's Arudino Control Jack's LED OffOn ConHTTP/1.1 200 OK Content-Type: text/html Connnection: cHTHTTP/1.1 200 OK Content-Type: text/html Connection: close ARDUINO_OK Type:HTTP/1.1 200 OK Content-Type: text/html Connection: clONe ARDUINO_OK ext/html ConnectiHTTP/1.1 200 OK ContHTTP/1.1 200 OK Content-Type: text/html Connection: close QUERY_OK6=ON,7=ON,8=ON,9=ON,Type: text/html Connnection: close Jack's Arudino Control Jack's LED OffOn tml Connect OffOn e ARDUINO_OK ontent-Type: text/html Connection: close ARHTTP/1.1 200 OK Content-TypeHTTP/1.1 200 OK Content-Type: text/html Connection: close ARDUINO_OK QUERY_OK6=OFF,7=ON,8=ON,9=ON,O_OK QUERY_OK6=OFF,7=ON,8=ON,9=ON, ARDUINO_OK HTTP/1.1 200 OK Content-Type: text/html CoHTTP/1.1HTTP/1.1 200 OK Content-Type: text/html Connnection: close Jack's Arudino ControHTTP/1.1 200 OK Content-Type: text/html Connnection: close HTTP/1.1 200 OK Content-Type: text/html Connection: close ARDUINO_OK e ARDUINO_OK HTTP/1.1 200 OK Content-Type: text/html ConnHTTP/1.1 200 OK Content-Type: text/html ConHTTP/1.1 200 OK HTTP/1.1 200 OK ContHTTP/1.1 200 OK Content-Type: text/html HTTP/1.1 200 OK Content-Type: text/HTTP/1.1 200 OK Content-Type: text/html Connection: close ARDUINO_OK QUERY_OK6=OFF,7=OFF,8=OFF,9=OFF,EFECTO1_OKEFECTO2_OKEFECTO3_OKEFECTO4_OKEFECTO5_OKEFECTO6_OK this repeats but I exeeded the post limit

some times this just works fine, but some times, it crashed... any idea?
any clue?

You probably ran out of memory. You use a lot of print/println calls without using the F() macro (holds the strings in the flash without using the same amount of RAM). And you're using the String class. Although the worst bug in it is fixed in version 1.0.5 of the IDE, it's still a bad choice for sketches that have to run reliably for a longer time because it uses dynamic memory allocation. That way the memory gets fragmented until there isn't a memory area of the requested size. At that point the results get erratic and your sketch isn't working in a predictable manner anymore.

Hi could you please explain me more about the F() macro? also how do I search for a substring on a string without using the string class.. any idea? please expand a little bit on that. THANKS!!! a lot

could you please explain me more about the F() macro?

You could use the F() macro with an class that inherits from the Print class, so almost any library that offers print() and println() methods is a candidate. Just add the macro around a string literal and you save the RAM:

client.print("This is just an example string literal");

gets

client.print(F("This is just an example string literal"));

also how do I search for a substring on a string without using the string class.

If you work with C strings (character arrays) you can use the strstr() function to search for substrings (http://www.cplusplus.com/reference/cstring/strstr/).

In an embedded platform with that limited memory it's even better to not store that string but parse it while it drops in. Usually that results in a bit more code but saves relevant amounts of memory, depending on the area of use, of course.

pylon really you rock ,.... I mostly solve it... basically I got a more clear working, but it seems that it is not flushing the string on after each reply... I do not know why... or how to flush an string rather than ="" so... basically I do not know how to do it...

in the other hand I will investigate the str function that you sent... and I will try to replace it.. but if you could please help me on the flushing stuff first? THANKS!

If flushing means setting it to be empty, use this:

readString = (char *)NULL;

That's the easiest way to call the (protected) method invalidate() which frees the occupied memory and sets the object to be empty.

Serial.println(F("connected"));
String DatatobeSent = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n\r";
DatatobeSent += "<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd="http://www.w3.org/2001/XMLSchema\" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/\">\n\r";
DatatobeSent += "soap:Body\n\r";
DatatobeSent += "<SampleData xmlns="http://tempuri.org">\n\r";
DatatobeSent += "34\n\r";
DatatobeSent += "\n\r";
DatatobeSent += "</soap:Body>\n\r";
DatatobeSent += "</soap:Envelope>\n\r";

Please help with above Code !! I am using Webservice developed in ASP.NET !! On Invoking SOAP Request from C# i am getting the same value which i sent using Parameter.

But in case of Arduino, it is always Blank !! i printed the string on serial before sending it to client, it shows data at the serial terminal. But on Repsonse i always get like this--->

HTTP/1.1 200 OK
Cache-Control: private, max-age=0
Content-Type: text/xml; charset=utf-8
Server: Microsoft-IIS/8.5
X-AspNet-Version: 4.0.30319
X-Powered-By: ASP.NET
X-Powered-By-Plesk: PleskWin
Date: Sun, 22 Jan 2017 09:19:20 GMT
Connection: close
Content-Length: 296

<?xml version="1.0" encoding="utf-8"?>

disconnecting.