GDP group 24 node core
Dependencies: EthernetInterface SDFileSystem mbed-rtos mbed snail MbedJSONValue
http.cpp
- Committer:
- Trumple
- Date:
- 2014-11-18
- Revision:
- 1:27b35752c5d0
- Child:
- 2:1cbb20dd1733
File content as of revision 1:27b35752c5d0:
#include "mbed.h" #include "http.h" #include <string> #include <vector> #include <sstream> http::http() { #ifdef DEBUG printf("[HTTP] Ethernet connecting...\r\n"); #endif eth.init(); eth.connect(); #ifdef DEBUG printf("[HTTP] Ethernet connected, IP: %s\r\n", eth.getIPAddress()); #endif } string http::get(string address, int port, string url, int replyTimeout) { #ifdef DEBUG printf("[HTTP] Sending GET request to %s%s\r\n", address.c_str(), url.c_str()); #endif TCPSocketConnection sock; sock.connect(address.c_str(), port); #ifdef DEBUG printf("[HTTP] Connected to endpoint...\r\n"); #endif string httpget = "GET " + url + " HTTP/1.1"; httpget += "\nHost: " + address + "\n\n"; //get a writable char* (I.E. not const char* returned by c_str), put it into a vector vector<char> writable(httpget.begin(), httpget.end()); writable.push_back('\0'); sock.send_all(&writable[0], writable.size()-1); string message = this->receiveFromSock(sock, replyTimeout); sock.close(); return this->parse(message); } string http::post(string address, int port, string url, string jsonPayload, int replyTimeout) { #ifdef DEBUG printf("[HTTP] Sending POST request to %s%s\r\n", address.c_str(), url.c_str()); #endif TCPSocketConnection sock; sock.connect(address.c_str(), port); #ifdef DEBUG printf("[HTTP] Connected to endpoint...\r\n"); #endif stringstream contentLength; contentLength << jsonPayload.size(); string contentLengthStr = contentLength.str(); string httppost = "POST " + url + " HTTP/1.1"; httppost += "\nHost: " + address; httppost += "\nContent-Type: application/json"; httppost += "\nContent-Length: " + contentLengthStr; httppost += "\n\n" + jsonPayload; //to get a writable char* (I.E. not const char* returned by string.c_str), put it into a vector vector<char> writable(httppost.begin(), httppost.end()); writable.push_back('\0'); sock.send_all(&writable[0], writable.size()-1); string message = this->receiveFromSock(sock, replyTimeout); sock.close(); return this->parse(message); } string http::receiveFromSock(TCPSocketConnection sock, int replyTimeout) { char buffer[1024]; int receiveByteCount; string message; while (true) { receiveByteCount = sock.receive(buffer, sizeof(buffer)-1);//spare a byte for null termination byte if (receiveByteCount <= 0) break; buffer[receiveByteCount] = '\0'; message += buffer; } return message; } string http::parse(string httpReply) { return httpReply; }