使用curl库, 正常的POST, GET, 大家都很熟悉,我就不讲解了, 但是当对方提供的接口只是一个 SOAP 接口时,我们该如何处理呢 ?
其实和POST没有什么大的区别, 无非就是 http 的header 不一样而已, 本质还是 HTTP协议, 只不过 HTTP 头家电鸡精而已。
下面的代码 给HTTP头添加了一个 SOAPAction: , 其他的地方和 POST 一样。
struct curl_slist *headers=NULL; headers = curl_slist_append(headers, "Content-Type: text/xml; charset=utf-8"); headers = curl_slist_append(headers, "SOAPAction: /"http://tempuri.org/ScheduleRecordNoticeV2/"");
SNPRINTF (buf, sizeof(buf)-1, "%s", g_Config.cmsWebservice); curl_handle = curl_easy_init(); if (curl_handle == NULL) { safe_free (postbuf); return ; } MemoryStruct *pmem = (MemoryStruct*)calloc (1, sizeof(MemoryStruct)); if (pmem == NULL) { safe_free (postbuf); return ; } const char* urlbuf = urlspace(buf); curl_easy_setopt(curl_handle, CURLOPT_URL, urlbuf); //curl_easy_setopt(curl_handle, CURLOPT_URL, urlbuf); curl_easy_setopt(curl_handle, CURLOPT_POSTFIELDS, postbuf); curl_easy_setopt(curl_handle, CURLOPT_POSTFIELDSIZE, strlen(postbuf)); curl_easy_setopt(curl_handle, CURLOPT_WRITEFUNCTION, ResponseXML_Callback); curl_easy_setopt(curl_handle, CURLOPT_WRITEDATA, (void *)pmem); curl_easy_setopt(curl_handle, CURLOPT_POST, 1); #ifdef _DEBUG curl_easy_setopt(curl_handle, CURLOPT_VERBOSE, 1L); #endif curl_easy_setopt(curl_handle, CURLOPT_HEADER, 1); res = curl_easy_setopt(curl_handle, CURLOPT_HTTPHEADER, headers); curl_easy_setopt(curl_handle, CURLOPT_FOLLOWLOCATION, 1); curl_easy_setopt(curl_handle, CURLOPT_USERAGENT, "libcurl-agent/1.0"); curl_easy_setopt(curl_handle, CURLOPT_COOKIEFILE, "./curlpost.cookie"); curl_easy_setopt(curl_handle, CURLOPT_CONNECTTIMEOUT, 15); // 设置连接超时,单位秒 curl_easy_setopt(curl_handle, CURLOPT_TIMEOUT, 60); res = curl_easy_perform(curl_handle); if (res != CURLE_OK) { curl_easy_cleanup(curl_handle); safe_free (pmem->mem); safe_free (pmem); safe_free (postbuf); curl_slist_free_all(headers); return ; }