Ver Fonte

Add HttpRequest::SetAuth

ithewei há 2 anos atrás
pai
commit
de6b8c4340
3 ficheiros alterados com 25 adições e 0 exclusões
  1. 5 0
      docs/cn/HttpMessage.md
  2. 15 0
      http/HttpMessage.cpp
  3. 5 0
      http/HttpMessage.h

+ 5 - 0
docs/cn/HttpMessage.md

@@ -81,6 +81,11 @@ class HttpRequest : public HttpMessage {
     // 设置代理
     void SetProxy(const char* host, int port);
 
+    // 设置认证
+    void SetAuth(const std::string& auth);
+    void SetBasicAuth(const std::string& username, const std::string& password);
+    void SetBearerTokenAuth(const std::string& token);
+
     // 设置请求超时
     void SetTimeout(int sec);
     // 设置连接超时

+ 15 - 0
http/HttpMessage.cpp

@@ -5,6 +5,7 @@
 #include "htime.h"
 #include "hlog.h"
 #include "hurl.h"
+#include "base64.h"
 
 using namespace hv;
 
@@ -735,6 +736,20 @@ void HttpRequest::SetProxy(const char* host, int port) {
     proxy = 1;
 }
 
+void HttpRequest::SetAuth(const std::string& auth) {
+    SetHeader("Authorization", auth);
+}
+
+void HttpRequest::SetBasicAuth(const std::string& username, const std::string& password) {
+    std::string strAuth = hv::asprintf("%s:%s", username.c_str(), password.c_str());
+    std::string base64Auth = hv::Base64Encode((const unsigned char*)strAuth.c_str(), strAuth.size());
+    SetAuth(std::string("Basic ") + base64Auth);
+}
+
+void HttpRequest::SetBearerTokenAuth(const std::string& token) {
+    SetAuth(std::string("Bearer ") + token);
+}
+
 std::string HttpRequest::Dump(bool is_dump_headers, bool is_dump_body) {
     ParseUrl();
 

+ 5 - 0
http/HttpMessage.h

@@ -455,6 +455,11 @@ public:
     void SetProxy(const char* host, int port);
     bool IsProxy() { return proxy; }
 
+    // Auth
+    void SetAuth(const std::string& auth);
+    void SetBasicAuth(const std::string& username, const std::string& password);
+    void SetBearerTokenAuth(const std::string& token);
+
     void SetTimeout(int sec) { timeout = sec; }
     void SetConnectTimeout(int sec) { connect_timeout = sec; }