其实如果这种实现,个人还是推荐脚本来搞,毕竟脚本方便些, 这里用c/c++,只是代码较方便,从之前写的项目中涉及到的一个curl部分
有管用什么实现,写出来只是希望大家需要注意: 业务层,通信层, 协议层(这里我先这么区别,为的是和下面的代码对应方便来说)
例如下面的代码中,标红色的地方表示针对业务层上的通信已完成(仅是通信完成,这里并不代表成功与否)
而绿色我把这描述成协议层,即通信完成情况下,协议层是否完成,
我举这个例子目的不是想说c/c++对应的curl如何来写,只是想表达程序我理解分三个层,第一是外部的业务逻辑,然后是通信层,最后是协议层
再例如一个需求,你把数据用protobuf封好后通过网络传输到另端的库中存储起来,那么这个过程可以描述为: 通信层通过rpc调用传输这个protobuf数据(此时通信层完成传输任务,他不管你到底这个protobuf入没入到库中),然后入到库中后反馈状态至业务层,业务层只有在通信与协议均正常下才为业务正常,否则表示需求没有达到要求
size_t WriteData(char *ptr, size_t size, size_t nmemb, void *out) {
((std::stringstream*)out)->write(ptr, size * nmemb);
return size * nmemb;
}
int Curl(std::string &url , std::map<std::string, std::string>&__map,) {
int ret_code = -1;
long httpcode = 0;
std::stringstream out;
string response = "";
//curl_global_init(CURL_GLOBAL_ALL);//declared in main()
CURL *easy_handle = curl_easy_init();
if (easy_handle == NULL) {
curl_easy_cleanup(easy_handle);
curl_global_cleanup();
return FAIL;
}
curl_easy_setopt(easy_handle, CURLOPT_TIMEOUT, 10);
curl_easy_setopt(easy_handle, CURLOPT_NOSIGNAL, 1L);
//curl_easy_setopt(easy_handle, CURLOPT_FORBID_REUSE, 1);
curl_easy_setopt(easy_handle, CURLOPT_WRITEFUNCTION, WriteData);
curl_easy_setopt(easy_handle, CURLOPT_WRITEDATA, &out);
curl_easy_setopt(easy_handle, CURLOPT_URL, url.c_str());
curl_easy_setopt(easy_handle, CURLOPT_HTTPGET,1L);
int ret_url = curl_easy_perform(easy_handle);
if(CURLE_COULDNT_CONNECT == ret_url || CURLE_OK != ret_url){
return FAIL;
}
curl_easy_getinfo( easy_handle, CURLINFO_RESPONSE_CODE, &httpcode );
if( 200 == httpcode ) {
response = out.str();
if(response.size() > 0) {
if(0){
;//ret_code = /*call function*/
}else{
ret_code = OK;
}
} else {
ret_code = ERROR_BUF_SIZE; // const int ERROR_BUF_SIZE = -3;
}
} else {
ret_code = FAIL;
}
curl_easy_cleanup(easy_handle);
curl_global_cleanup();
return ret_code;
}