前面的文章《Libcurl编译指南——Android和Windows系统》已经就libcurl在Windows和Android系统编做了详细的说明。
本文档用C/C++实现简单的HTTP/HTTPS客户端,支持get和post,支持保持session和长连接。
httpConn.h
#ifndef __HTTP_CONN_H__
#define __HTTP_CONN_H__
#include "curl.h"
#define RETRY_TIMES 3
struct MemoryStruct {
char *memory;
unsigned int size;
};
class RequestHandler
{
private:
public:
MemoryBlock request;
MemoryBlock response;
int http_code;
};
class HttpRequest
{
private:
CURL *curl_handle;
CURLcode curl_res;
long http_code;
struct MemoryStruct receive_header;
struct MemoryStruct receive_content;
struct MemoryStruct error_message;
struct curl_slist *http_headers;
int retry_times;
public:
HttpRequest();
~HttpRequest();
int setRequestUrl(const char *url); // 设置URL
int setRequestHeader(const char *header); // 设置Header
int setRequestTimeout(long time); // 设置超时时间
int setPostData(const char *data, unsigned int size); // 设置post数据
int setResultCallback(); // 回调
int performRequest(); // 发送数据
int sendReceiveEx(const char *url, RequestHandler *handler); // 发送和接收url请求
int getHttpCode(); //返回http code
int getHeader(char *header, unsigned int *len); // 返回Header
int getContent(char *content, unsigned int *len);
};
#endif
httpConn.cpp
#include "httpConn.h"
#include "curl.h"
static unsigned int RetriveContentCallback(void *contents, unsigned int size, unsigned int nmemb, void *userp)
{
unsigned int realsize = size * nmemb;
struct MemoryStruct *mem = (struct MemoryStruct *)userp;
char *ptr = (char*)realloc((void *)mem->memory, mem->size + realsize + 1);
if (ptr == NULL) {
/* out of memory! */
printf("not enough memory (realloc returned NULL)\n");
return -6;
}
mem->memory = ptr;
memcpy(&(mem->memory[mem->size]), contents, realsize);
mem->size += realsize;
mem->memory[mem->size] = 0;
return realsize;
}
static unsigned int RetriveHeaderCallback(void *contents, unsigned int size, unsigned int nmemb, void *userp)
{
unsigned int realsize = size * nmemb;
struct MemoryStruct *mem = (struct MemoryStruct *)userp;
char *ptr = (char*)realloc((void *)mem->memory, mem->size + realsize + 1);
if (ptr == NULL) {
/* out of memory! */
printf("not enough memory (realloc returned NULL)\n");
return -6;
}
mem->memory = ptr;
memcpy(&(mem->memory[mem->size]), contents, realsize);
mem->size += realsize;
mem->memory[mem->size] = 0;
return realsize;
}
HttpRequest::HttpRequest()
{
curl_res = CURLE_OK;
http_code = 0;
curl_handle = NULL;
http_headers = NULL;
retry_times = RETRY_TIMES;
/* will be grown as needed by the realloc above */
receive_content.memory = (char*)malloc(1);
receive_header.memory = (char*)malloc(1);
error_message.memory = (char*)malloc(1);
/* no data at this point */
receive_content.size = 0;
receive_header.size = 0