This is a quick example of a simple HTTP client program using the network-socket API that is provided as a part of mbed-os. The program brings up an underlying network interface, and uses it to perform an HTTP transaction over a TCPSocket.

Files at this revision

API Documentation at this revision

Comitter:
mbed_official
Date:
Wed Aug 15 11:15:04 2018 +0100
Parent:
55:70c9ae73c998
Child:
57:524f671184a6
Commit message:
Improve error handling.

* socket.connect() was not causing program to stop, in case of error
* socket.send() was printing "Error! socket.connect()..." in case of error
* rename labels to upper case for readability

.
Commit copied from https://github.com/ARMmbed/mbed-os-example-sockets

Changed in this revision

main.cpp Show annotated file Show diff for this revision Revisions of this file
--- a/main.cpp	Tue Aug 14 14:00:07 2018 +0100
+++ b/main.cpp	Wed Aug 15 11:15:04 2018 +0100
@@ -40,6 +40,10 @@
 
     // Open a socket on the network interface, and create a TCP connection to mbed.org
     TCPSocket socket;
+    // Send a simple http request
+    char sbuffer[] = "GET / HTTP/1.1\r\nHost: api.ipify.org\r\nConnection: close\r\n\r\n";
+    nsapi_size_t size = strlen(sbuffer);
+
     r = socket.open(net);
     if (r != 0) {
         printf("Error! socket.open() returned: %d\n", r);
@@ -48,18 +52,15 @@
     r = socket.connect("api.ipify.org", 80);
     if (r != 0) {
         printf("Error! socket.connect() returned: %d\n", r);
+        goto DISCONNECT;
     }
 
-    // Send a simple http request
-    char sbuffer[] = "GET / HTTP/1.1\r\nHost: api.ipify.org\r\nConnection: close\r\n\r\n";
-    nsapi_size_t size = strlen(sbuffer);
-
     // Loop until whole request send
     while(size) {
         r = socket.send(sbuffer+r, size);
         if (r < 0) {
-            printf("Error! socket.connect() returned: %d\n", r);
-            goto disconnect;
+            printf("Error! socket.send() returned: %d\n", r);
+            goto DISCONNECT;
         }
         size -= r;
         printf("sent %d [%.*s]\n", r, strstr(sbuffer, "\r\n")-sbuffer, sbuffer);
@@ -76,7 +77,7 @@
     }
     if (r < 0) {
         printf("Error! socket.recv() returned: %d\n", r);
-        goto disconnect;
+        goto DISCONNECT;
     }
 
     printf("recv %d [%.*s]\n", rcount, strstr(buffer, "\r\n")-buffer, buffer);
@@ -86,7 +87,7 @@
     printf("External IP address: %.*s\n", rcount-(p-buffer), p);
     delete[] buffer;
 
-disconnect:
+DISCONNECT:
     // Close the socket to return its memory and bring down the network interface
     socket.close();