88 lines
2.7 KiB
C++
88 lines
2.7 KiB
C++
//
|
|
// Created by linbo on 2025/6/24.
|
|
//
|
|
|
|
#ifndef HTTPCLIENT_H
|
|
#define HTTPCLIENT_H
|
|
#include <string>
|
|
#include <map>
|
|
#include <vector>
|
|
#include <stdexcept>
|
|
#include <memory>
|
|
#include <utility>
|
|
|
|
// 控制是否使用libcurl的宏
|
|
#ifdef USE_LIBCURL
|
|
#include <curl/curl.h>
|
|
#endif
|
|
|
|
using namespace std;
|
|
|
|
namespace cmvr {
|
|
|
|
// HTTP响应结构
|
|
struct HttpResponse {
|
|
int statusCode;
|
|
std::string statusText;
|
|
std::map<std::string, std::string> headers;
|
|
std::string body;
|
|
};
|
|
|
|
// HTTP异常类
|
|
class HttpException : public std::runtime_error {
|
|
public:
|
|
HttpException(const std::string& message) : std::runtime_error(message) {}
|
|
};
|
|
|
|
// HTTP客户端接口
|
|
class HttpClientImpl {
|
|
public:
|
|
virtual ~HttpClientImpl() = default;
|
|
|
|
virtual void setBaseUrl(const std::string& baseUrl) = 0;
|
|
virtual void setTimeout(int timeout) = 0;
|
|
virtual void addHeader(const std::string& key, const std::string& value) = 0;
|
|
virtual void clearHeaders() = 0;
|
|
|
|
virtual HttpResponse get(const std::string& path,
|
|
const std::map<std::string, std::string>& params = {}) = 0;
|
|
|
|
virtual HttpResponse post(const std::string& path,
|
|
const std::map<std::string, std::string>& params = {},
|
|
const std::string& body = "",
|
|
const std::string& contentType = "application/x-www-form-urlencoded") = 0;
|
|
|
|
virtual HttpResponse postJson(const std::string& path,
|
|
const std::map<std::string, std::string>& params = {},
|
|
const std::string& jsonBody = "") = 0;
|
|
};
|
|
|
|
// HTTP客户端类
|
|
class HttpClient {
|
|
public:
|
|
HttpClient();
|
|
~HttpClient() = default;
|
|
|
|
void setBaseUrl(const std::string& baseUrl);
|
|
void setTimeout(int timeout);
|
|
void addHeader(const std::string& key, const std::string& value);
|
|
void clearHeaders();
|
|
|
|
HttpResponse get(const std::string& path,
|
|
const std::map<std::string, std::string>& params = {});
|
|
|
|
HttpResponse post(const std::string& path,
|
|
const std::map<std::string, std::string>& params = {},
|
|
const std::string& body = "",
|
|
const std::string& contentType = "application/x-www-form-urlencoded");
|
|
|
|
HttpResponse postJson(const std::string& path,
|
|
const std::map<std::string, std::string>& params = {},
|
|
const std::string& jsonBody = "");
|
|
|
|
private:
|
|
std::unique_ptr<HttpClientImpl> m_impl;
|
|
};
|
|
|
|
}
|
|
#endif //HTTPCLIENT_H
|