SimpleSocket 1.0 examples

Dependencies:   EthernetNetIf SimpleSocket 1.0 mbed

Revision:
40:84182fc63956
Parent:
39:108499af2b53
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/examples/supertweet.cpp	Mon Feb 04 09:04:25 2013 +0000
@@ -0,0 +1,87 @@
+#include "EthernetNetIf.h"
+#include "SimpleSocket.h"
+#include <ctype.h>
+
+void encodeBase64(char *ibuf, char *obuf);
+int encodeFormUrl(char *s, char *t);
+
+void supertweet() {
+    EthernetNetIf eth;
+    eth.setup();
+    ClientSocket client("66.180.175.246", 80); // api.supertweet.net
+
+    char user[16], password[16], message[64] = {};
+    printf("user => ");
+    scanf("%s", user);
+    printf("password => ");
+    scanf("%s", password);
+    printf("message => ");
+    int c = 0;
+    while (c < ' ' || 0x7E < c)
+        c = getc(stdin);
+    ungetc(c, stdin);
+    for (int i = 0; i < sizeof(message) - 1 && (c = getc(stdin)) >= ' '; i++)
+        message[i] = c;
+
+    char credential[48], credential2[64], message2[256];
+
+    sprintf(credential, "%s:%s", user, password);
+    encodeBase64(credential, credential2);
+    encodeFormUrl(message, message2);
+
+    const char *request =
+        "POST /1/statuses/update.xml HTTP/1.1\r\n"
+        "Host: api.supertweet.net\r\n"
+        "Authorization: Basic %s\r\n"
+        "Content-Length: %d\r\n"
+        "Content-Type: application/x-www-form-urlencoded\r\n"
+        "\r\n"
+        "status=%s";
+
+    client.printf(request, credential2, strlen(message2) + 7,  message2);
+    printf(request, credential2, strlen(message2) + 7,  message2);
+    printf("\n");
+
+    while (client) {
+        if (client.available()) {
+            while (client.available()) {
+                char response[128] = {};
+                client.read(response, sizeof(response) - 1);
+                printf("%s", response);
+            }
+            client.close();
+        }
+    }
+    printf("\ndone\n");
+}
+
+int encodeFormUrl(char *s, char *t) {
+    char *head = t;
+    for (char c; (c = *s) != 0; s++)
+        switch (c) {
+            case '\r':
+                break;
+            case ' ' :
+                *t++ = '+';
+                break;
+            default:
+                t += sprintf(t, isalnum(c) ? "%c" : (c == '\n') ? "\r%c" : "%%%02X", c);
+        }
+    *t = '\0';
+    return t - head;
+}
+
+void encodeBase64(char ibuf[], int length, char *obuf) {
+    const char BASE64[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
+    int i, j;
+    for (i = j = 0; j < length; j += 3, i += 4) {
+        long a = ibuf[j] << 16 | (j + 1 < length ? ibuf[j + 1] << 8 : 0) | (j + 2 < length ? ibuf[j + 2] : 0);
+        for (int k = 3; k >= 0; k--, a >>= 6)
+            obuf[i + k] = (j + k - 1) < length ? BASE64[a & 63] : '=';
+    }
+    obuf[i] = '\0';
+}
+
+void encodeBase64(char *ibuf, char *obuf) {
+    encodeBase64(ibuf, strlen(ibuf), obuf);
+}
\ No newline at end of file