给我一份C++http调用web服务接口代码
时间: 2023-09-25 11:06:37 浏览: 73
### 回答1:
#include <stdio.h>
#include <curl/curl.h>int main(void)
{
CURL *curl;
CURLcode res;
curl = curl_easy_init();
if(curl) {
curl_easy_setopt(curl, CURLOPT_URL, "http://example.com/");
/* Perform the request, res will get the return code */
res = curl_easy_perform(curl);
/* Check for errors */
if(res != CURLE_OK)
fprintf(stderr, "curl_easy_perform() failed: %s\n",
curl_easy_strerror(res));
/* always cleanup */
curl_easy_cleanup(curl);
}
return 0;
}答案:这是用C语言调用Web服务接口的示例代码:
### 回答2:
以下是一个基本的C语言代码示例,用于调用web服务接口:
```c
#include <stdio.h>
#include <stdlib.h>
#include <curl/curl.h>
int main(void) {
CURL *curl;
CURLcode res;
curl_global_init(CURL_GLOBAL_DEFAULT);
curl = curl_easy_init();
if(curl) {
// 设置web服务接口的URL
curl_easy_setopt(curl, CURLOPT_URL, "http://example.com/api/endpoint");
// 设置要发送的数据,如果有的话
// curl_easy_setopt(curl, CURLOPT_POSTFIELDS, "param1=value1¶m2=value2");
// 执行HTTP GET请求
res = curl_easy_perform(curl);
if(res != CURLE_OK) {
fprintf(stderr, "curl_easy_perform() failed: %s\n", curl_easy_strerror(res));
}
// 清理curl句柄
curl_easy_cleanup(curl);
}
curl_global_cleanup();
return 0;
}
```
上述代码使用了libcurl库来进行web服务接口调用。首先需要包含`<curl/curl.h>`头文件,并使用`curl_global_init()`函数进行初始化。然后使用`curl_easy_init()`函数创建一个CURL句柄。通过调用`curl_easy_setopt()`函数来设置CURL选项,例如设置要访问的URL、要发送的数据等。最后使用`curl_easy_perform()`函数执行HTTP请求并获取返回结果。
这只是一个简单的示例,你还可以根据实际需求设置更多的CURL选项。注意,如果你的系统中没有安装libcurl库,可能需要先安装该库才能编译和运行上述代码。