httpAccess.cpp
00001
00002
00003
00004
00005
00006
00007 #include "httpAccess.h"
00008
00009
00010 HttpAccess::HttpAccess(const char *web_server, int web_port)
00011 : server(web_server), port(web_port), items(string()) {
00012 }
00013
00014
00015 HttpAccess::~HttpAccess(void) {
00016 }
00017
00018
00019 string HttpAccess::sendRequest(SocketCtrl& socket,
00020 const char *request, int size, int timeout) {
00021
00022 SocketSet socket_set;
00023 socket_set.add(socket);
00024
00025 socket_set.check();
00026 socket.send(request, size);
00027 if (timeout == 0) {
00028 return string();
00029 }
00030
00031 int retval = socket_set.check(timeout);
00032 char buf[BUFSIZ];
00033 int n = socket.recv(buf, sizeof(buf)-1);
00034 if ((retval == 0) || (n <= 0)) {
00035 return string();
00036 }
00037
00038 buf[n] = '\0';
00039 char *pBody = strstr((const char *)buf, "\r\n\r\n");
00040 if (pBody == NULL) {
00041 return string();
00042 }
00043 pBody += 4;
00044 int body = pBody - buf;
00045
00046 string htmlText = string(buf, body, n - body);
00047 do {
00048 retval = socket_set.check(timeout);
00049 n = socket.recv(buf, sizeof(buf)-1);
00050 if (n > 0) {
00051 buf[n] = '\0';
00052 htmlText += string(buf, 0, n);
00053 }
00054 } while ((retval > 0) && (n > 0));
00055
00056 return htmlText;
00057 }
00058
00059
00060 string HttpAccess::getHtmlText(const char *path, int timeout) {
00061
00062 SocketCtrl tcp_socket = SocketCtrl(server.c_str(), port);
00063
00064 string request =
00065 "GET " + string(path) + " HTTP/1.0\n"
00066 "Host: " + server + "\n"
00067 "\n";
00068
00069 return sendRequest(tcp_socket, request.c_str(), request.size(), timeout);
00070 }
00071
00072
00073 HttpAccess& HttpAccess::clearPutItem(void) {
00074
00075 items = string();
00076 return *this;
00077 }
00078
00079
00080 HttpAccess& HttpAccess::addPutItem(const char *title, const char *value) {
00081
00082 if (items.size() > 0) {
00083 items += "&";
00084 }
00085 items += string(title) + "=" + string(value);
00086
00087 return *this;
00088 }
00089
00090
00091 string HttpAccess::sendPutItem(const char *path, int timeout) {
00092 SocketCtrl socket = SocketCtrl(server.c_str(), port);
00093
00094 char size[11];
00095 sprintf(size, "%d", items.size());
00096 string request =
00097 "POST " + string(path) + " HTTP/1.0\n"
00098 "Host: " + server + "\n"
00099 "Content-Type: application/x-www-form-urlencoded\n"
00100 "Content-Length: " + size + "\n"
00101 "\n"
00102 + items + "\n"
00103 "\n";
00104
00105 return sendRequest(socket, request.c_str(), request.size(), timeout);
00106 }
00107