wrapper of TLS library to connect to HTTPS servers
Dependents: HTTPSClientExample
HTTPSClient.cpp
00001 #include "HTTPSClient.h" 00002 #include "HTTPHeader.h" 00003 #include <stdio.h> 00004 #include <string.h> 00005 00006 HTTPSClient::HTTPSClient(): 00007 _con() 00008 { 00009 } 00010 00011 bool HTTPSClient::connect(const std::string& host) 00012 { 00013 if(_con.is_connected()) 00014 return false; 00015 00016 return _con.connect(host.c_str()); 00017 } 00018 00019 std::string HTTPSClient::readLine() 00020 { 00021 std::string line; 00022 char c; 00023 _con.receive(&c, 1); 00024 while(c != '\r') { 00025 line += c; 00026 _con.receive(&c, 1); 00027 } 00028 _con.receive(&c, 1); // skip \n 00029 return line; 00030 } 00031 00032 HTTPHeader HTTPSClient::readHeader() 00033 { 00034 HTTPHeader hdr; 00035 std::string line = readLine(); 00036 sscanf(line.c_str(), "HTTP/1.%*d %d OK", &hdr._status); 00037 do { 00038 if(!line.compare(0,strlen("Content-Length"), "Content-Length")) 00039 sscanf(line.c_str(), "Content-Length: %d", &hdr._bodyLength); 00040 else if(!line.compare(0,strlen("content-length"), "content-length")) 00041 sscanf(line.c_str(), "content-length: %d", &hdr._bodyLength); 00042 line = readLine(); 00043 } while(line.size()); 00044 return hdr; 00045 } 00046 00047 int HTTPSClient::get(const std::string& path, HTTPHeader *hdr) 00048 { 00049 if(!_con.is_connected()) 00050 return -1; 00051 00052 const std::string &request = HTTPHeader::getRequest(path, _con.get_address(), 443); 00053 00054 if(_con.send_all((char*)request.c_str(), request.size()+1) != request.size()+1) 00055 return -1; 00056 00057 *hdr = readHeader(); 00058 return hdr->_status == HTTP_OK ? 0 : -1; 00059 } 00060 00061 int HTTPSClient::get(const std::string& path, HTTPHeader *hdr, char *data, int length) 00062 { 00063 if(!_con.is_connected()) 00064 return -1; 00065 00066 if(hdr != NULL) { 00067 const std::string &request = HTTPHeader::getRequest(path, _con.get_address(), 443); 00068 if(_con.send_all((char*)request.c_str(), request.size()+1) != request.size()+1) 00069 return -1; 00070 *hdr = readHeader(); 00071 if(hdr->_status != HTTP_OK) 00072 return -1; 00073 00074 if(hdr->_bodyLength > 0) 00075 return _con.receive(data, hdr->_bodyLength > length ? length : hdr->_bodyLength); 00076 00077 return 0; 00078 } else 00079 return _con.receive(data, length); 00080 } 00081 00082 bool HTTPSClient::disconnect() 00083 { 00084 if(!_con.is_connected()) 00085 return true; 00086 00087 return _con.close() == 0; 00088 }
Generated on Thu Jul 21 2022 11:27:49 by 1.7.2