httpAccess.cpp

00001 /*
00002   HTTP アクセス
00003   Satofumi KAMIMURA
00004   $Id$
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("") {
00012 }
00013 
00014 
00015 HttpAccess::~HttpAccess(void) {
00016 }
00017 
00018 
00019 std::string HttpAccess::sendRequest(const char *request,
00020                                     int size, int timeout) {
00021 
00022   TcpipDevice socket;
00023   if (socket.connect(server.c_str(), port) < 0) {
00024     return "";
00025   }
00026 
00027   socket.send(request, size);
00028   if (timeout == 0) {
00029     return "";
00030   }
00031 
00032   char buf[BUFSIZ];
00033   int n = socket.recv(buf, sizeof(buf)-1, timeout);
00034   if (n <= 0) {
00035     return "";
00036   }
00037 
00038   buf[n] = '\0';
00039   char *pBody = strstr((const char *)buf, "\r\n\r\n");
00040   if (pBody == NULL) {
00041     return "";
00042   }
00043   pBody += 4;
00044   int body = pBody - buf;
00045 
00046   std::string htmlText(buf, body, n - body);
00047   do {
00048     n = socket.recv(buf, sizeof(buf)-1, timeout);
00049     if (n > 0) {
00050       buf[n] = '\0';
00051       htmlText += std::string(buf, 0, n);
00052     }
00053   } while (n > 0);
00054 
00055   return htmlText;
00056 }
00057 
00058 
00059 std::string HttpAccess::getHtmlText(const char *path, int timeout) {
00060 
00061   std::string request =
00062     "GET " + std::string(path) + " HTTP/1.0\n"
00063     "Host: " + server + "\n"
00064     "\n";
00065 
00066   return sendRequest(request.c_str(), request.size(), timeout);
00067 }
00068 
00069 
00070 HttpAccess& HttpAccess::clearItems(void) {
00071 
00072   items = "";
00073   return *this;
00074 }
00075 
00076 
00077 HttpAccess& HttpAccess::addItem(const char *title, const char *value) {
00078 
00079   if (items.size() > 0) {
00080     items += "&";
00081   }
00082   items += std::string(title) + "=" + std::string(value);
00083 
00084   return *this;
00085 }
00086 
00087 
00088 HttpAccess& HttpAccess::addItem(const char *title, int value) {
00089 
00090   char value_str[13];
00091   sprintf(value_str, "%d", value);
00092   return addItem(title, value_str);
00093 }
00094 
00095 
00096 std::string HttpAccess::sendPostRequest(const char *path, int timeout) {
00097 
00098   char size[11];
00099   sprintf(size, "%d", items.size());
00100   std::string request =
00101     "POST " + std::string(path) + " HTTP/1.0\n"
00102     "Host: " + server + "\n"
00103     "Content-Type: application/x-www-form-urlencoded\n"
00104     "Content-Length: " + size + "\n"
00105     "\n"
00106     + items + "\n"
00107     "\n";
00108 
00109   return sendRequest(request.c_str(), request.size(), timeout);
00110 }
00111 

Generated on Mon Apr 13 22:52:01 2009 by  doxygen 1.5.7.1