一个http get请求的用法
curl工具命令行运行正常,请求网址返回welcome to the photoshop API
请问怎么用c++怎么实现?下面执行出来是空的,什么也没获取到,写法有没有什么问题呢
#include <iostream>
#include <curl/curl.h>
using namespace std;
/* 不考虑任何异常的情况, 简单的get请求 */
/***
* buffer 接收数据所在的缓冲区
* size 要读取的字节数
* count 读写size长度的数据count次
* response 用户自定义文件指针
*/
size_t getUrlResponse(char* buffer, size_t size, size_t count, string* response) {
size_t recv_size = size * count;
response->clear();
response->append(buffer);
return recv_size;
}
string get(const string& url) {
// 请求数据
string response;
// easy handle声明
CURL *handle;
// 初始化handle
handle = curl_easy_init();
// 设置url
curl_easy_setopt(handle, CURLOPT_URL, url.c_str());
//设置curl的请求头
struct curl_slist* header_list = NULL;
header_list = curl_slist_append(header_list, "Authorization:Bearer eyJhbGciOiJSUzI1NiIsIng1dSI6Imltc19uYTEta2V5LTEuY2VyIn0.eyJpZCI6IjE2MTk0MzEyNTYwNjdfNWNjNzNmNTItODhkYS00NzI4LWI4MzktN2M0MjMxYzM0NDQwX3VlMSIsImNsaWVudF9pZCI6ImUyMDk2MTc3ZTEzZjRhZDg5YzliZGE0ODliNzgyNGUxIiwidXNlcl9pZCI6IjUwODc3NjgxNjA4Njg2M0EwQTQ5NUM3MUB0ZWNoYWNjdC5hZG9iZS5jb20iLCJ0eXBlIjoiYWNjZXNzX3Rva2VuIiwiYXMiOiJpbXMtbmExIiwiYWFfaWQiOiI1MDg3NzY4MTYwODY4NjNBMEE0OTVDNzFAdGVjaGFjY3QuYWRvYmUuY29tIiwiZmciOiJWTUxKUlRPNUZMTzVOSE1HU01aTFZIUUFWTT09PT09PSIsIm1vaSI6IjgzNjljMDY2IiwiZXhwaXJlc19pbiI6Ijg2NDAwMDAwIiwic2NvcGUiOiJvcGVuaWQsQWRvYmVJRCxyZWFkX29yZ2FuaXphdGlvbnMiLCJjcmVhdGVkX2F0IjoiMTYxOTQzMTI1NjA2NyJ9.Fve8x2oBauAFWcAjTnhhlBXVQ3V5wvLjb-sgSFdohueXMCtOd8rsWkPeRX6QwYfJXah3j8v5raIG2mCS0yIqP7YAOero5Cx2D0jIaysd0dZmZfS3mxA9VgkISzP2L7uSicHc2es3i5zBCoztcn-4v15qUHOFWd2X1AKF5xadiRVwJG8IQaiJots6BoX9jxIt4PjZN8DkuSDK9HtkOMYwhoc0C8fXonAGUMt3IE7bFLI7kj7MlexhR-y8maa2Cx_THxtSmkp2BdLKeYRI9TQ5YEY6tUgPTKqcNG_JNAriCWCuKhPsBXrdmWZkBqKniuepNHIcJo0_W_L-k4kGF290kA");
header_list = curl_slist_append(header_list, "x-api-key:e2096177e13f4ad89c9bda489b7824e1");
curl_easy_setopt(handle, CURLOPT_HTTPHEADER, header_list);
//curl_easy_setopt(handle, CURLOPT_HTTPGET, NULL);
// 注册回调函数
curl_easy_setopt(handle, CURLOPT_WRITEFUNCTION, &getUrlResponse);
// 获取信息
curl_easy_setopt(handle, CURLOPT_WRITEDATA, &response);
// 执行请求
curl_easy_perform(handle);
// 释放
curl_easy_cleanup(handle);
return response;
}
int main() {
// 使用前初始化libcurl, 只需初始化一次
curl_global_init(CURL_GLOBAL_DEFAULT);
// 执行请求
cout << get("https://image.adobe.io/pie/psdService/hello");
// 释放libcurl相关资源
curl_global_cleanup();
return 0;
}