64,648
社区成员
发帖
与我相关
我的任务
分享
//network.h
#pragma once
#include "../curl/include/curl/curl.h"
#ifdef _DEBUG
# pragma comment(lib, "libcurl_d.lib")
#else
# pragma comment(lib, "libcurl.lib")
#endif
struct MemoryStruct {
char *memory;
size_t size;
};
class Http_request{
public:
Http_request();
~Http_request();
size_t Http_post_data(LPCSTR url, LPCSTR data);
size_t Http_file_upload();
private:
static size_t WriteMemoryCallback(void *contents, size_t size, size_t nmemb, void *userp);
public:
struct MemoryStruct chunk;
};
//network.cpp
#include "network.h"
Http_request::Http_request(){
chunk.memory = (char *)malloc(1); /* will be grown as needed by realloc above */
chunk.size = 0; /* no data at this point */
}
Http_request::~Http_request(){
free(chunk.memory);
}
size_t Http_request::Http_post_data(LPCSTR url, LPCSTR data)
{
CURL *curl;
CURLcode res;
curl_global_init(CURL_GLOBAL_ALL);
curl = curl_easy_init();
if (curl) {
curl_easy_setopt(curl, CURLOPT_URL, url);
/* send all data to this function */
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteMemoryCallback);
/* we pass our 'chunk' struct to the callback function */
curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void *)&chunk);
/* some servers don't like requests that are made without a user-agent
field, so we provide one */
curl_easy_setopt(curl, CURLOPT_USERAGENT, "libcurl-agent/1.0");
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, data);
/* if we don't provide POSTFIELDSIZE, libcurl will strlen() by
itself */
curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, (long)strlen(data));
/* 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));
}
else {
/*
* Now, our chunk.memory points to a memory block that is chunk.size
* bytes big and contains the remote file.
*
* Do something nice with it!
*/
printf("%s\n", chunk.memory);
}
/* always cleanup */
curl_easy_cleanup(curl);
/* we're done with libcurl, so clean it up */
curl_global_cleanup();
}
return chunk.size;
}
size_t Http_request::Http_file_upload(){
return 0;
}
size_t Http_request::WriteMemoryCallback(void *contents, size_t size, size_t nmemb, void *userp)
{
size_t realsize = size * nmemb;
struct MemoryStruct *mem = (struct MemoryStruct *)userp;
mem->memory = (char *)realloc(mem->memory, mem->size + realsize + 1);
if (mem->memory == NULL) {
/* out of memory! */
//printf("not enough memory (realloc returned NULL)\n");
return 0;
}
memcpy(&(mem->memory[mem->size]), contents, realsize);
mem->size += realsize;
mem->memory[mem->size] = 0;
return realsize;
}