It get the like count of Facebook.

Dependencies:   EthernetInterface HTTPClient mbed-rtos mbed

Fork of HTTPClient_HelloWorld by Donatien Garnier

main.cpp

Committer:
okini3939
Date:
2013-12-22
Revision:
3:7ad266ae429f
Parent:
2:270e2d0bb85a

File content as of revision 3:7ad266ae429f:

#include "mbed.h"
#include "EthernetInterface.h"
#include "HTTPClient.h"
#include <string.h>
#include <ctype.h>

#define URL "https://www.facebook.com/mbedmicro"

EthernetInterface eth;

int urlencode (char *str, char *buf, int len);

int facebookLikes (char *target) {
    HTTPClient http;
    char url[256], buf[1024];
    char *s;

    strcpy(url, "http://graph.facebook.com/");
    urlencode(target, &url[strlen(url)], sizeof(url) - strlen(url));
//    printf("url: %s\r\n", url);

    if (http.get(url, buf, sizeof(buf))) return -1;

    s = strstr(buf, "\"likes\":");
    if (s == NULL) return -1;
    s += 8;
    return atoi(s);
}

int main() 
{
    eth.init(); //Use DHCP
    eth.connect();
    printf("IP: %s\r\n", eth.getIPAddress());

    printf("Target: %s\r\n", URL);
    printf("Likes: %d\r\n", facebookLikes(URL));
    
    eth.disconnect();  
}


int to_hex (int code) {
  static char hex[] = "0123456789abcdef";
  return hex[code & 15];
}

/* urlencode code from 
 * Copyright (c) 2010 Donatien Garnier (donatiengar [at] gmail [dot] com)
 */
int urlencode (char *str, char *buf, int len) {
//  char *pstr = str, *buf = (char*)malloc(strlen(str) * 3 + 1), *pbuf = buf;
    char *pstr = str, *pbuf = buf;

    if (len < (strlen(str) * 3 + 1)) return -1;
    while (*pstr) {
        if (isalnum(*pstr) || *pstr == '-' || *pstr == '_' || *pstr == '.' || *pstr == '~') 
            *pbuf++ = *pstr;
        else if (*pstr == ' ') 
            *pbuf++ = '+';
        else 
            *pbuf++ = '%', *pbuf++ = to_hex(*pstr >> 4), *pbuf++ = to_hex(*pstr & 15);
        pstr++;
    }
    *pbuf = '\0';
    return 0;
}