examples for SimpleSocket/EthernetInterface
Dependencies: EthernetInterface SimpleSocket mbed-rtos mbed
Diff: examples/supertweet.cpp
- Revision:
- 0:6dc3cfd058c6
diff -r 000000000000 -r 6dc3cfd058c6 examples/supertweet.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/examples/supertweet.cpp Mon Feb 04 09:29:18 2013 +0000 @@ -0,0 +1,84 @@ +#include "SimpleSocket.h" +#include <ctype.h> + +void encodeBase64(char *ibuf, char *obuf); +int encodeFormUrl(char *s, char *t); + +void supertweet() { + 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