|
guocongbin | 12/07 2006, 02:38
因为要进行网络应用方面的编程,所以在网上找到了这个CommonC++的库。这是GNU的一个项目,我下载的版本是1 .5.3。 它里面提供的功能倒是很全面,体积也比较小巧,所以还是值得利用。不过里面的bug也不少,有些还是比较低级的bug。 我写了一个使用POST方法访问HTTP服务器的case,用来得到天气预报信息(服务就是前面的文章中提到的得到天气预报的web service服务)。 case的代码使用CommonC++自带的urlfetch.cpp该过来的 // myurlfeth.cpp #include <cc++/common.h> #include <iostream> #include <cstdlib>
#ifdef CCXX_NAMESPACES using namespace std; using namespace ost; #endif
class myURLStream : public URLStream { private: void httpHeader(const char *header, const char *value) { cout << "HEADER " << header << "=" << value << endl; } };
int main(int argc, char **argv) { myURLStream url; url.setProtocol(URLStream::protocolHttp1_1);
char cbuf[1024]; int len; #ifdef CCXX_EXCEPTIONS try { #endif char* surl = "http://www.xview.com.cn/WebService/Weather.asmx/GetWeatherDataSet"; char* city="北京"; char *var = "cityName"; char buf[30]; urlEncode(city, buf, 30); const char* para[3]; para[0] = (const char*)var; para[1] = buf; para[2] = NULL; url.post(surl,para, 1); cout << "loading..." << endl; while(!url.eof()) { url.read(cbuf, sizeof(cbuf)); len = url.gcount(); if(len > 0) cout.write(cbuf, len); } url.close(); cout << ends; #ifdef CCXX_EXCEPTIONS } catch(...) { cerr << "url fetch failed" << endl; } #endif return 0; }
不过要让这段代码工作,需要修改src/url.cpp,修正其中的两个bug 将src/url.cpp的第666行的switch...case结构修改如下
// src/url.cpp, line 666 switch(urlmethod) { case methodHttpPost: // get the content-length of request. // use '&' or '=' to connect different parameter, // therefore the total length is the length of all vars plus count -1 while(*args) { var = *args; bool alone = strchr(var, '='); len += strlen(var); count++; ++args; } len += count -1; count = 0; //len += 2; //guocb str << "Content-Type: application/x-www-form-urlencoded" << "rn"; str << "Content-Length: " << (unsigned)len << "rn"; break; case methodHttpPostMultipart: while(*args) str << *(args++) << "rn"; default: break; }
Comments
Add comment
|