void *HTTPClient::requestLoop(void *data) { HTTPClient * httpCli = (HTTPClient*)data; while(1) { //Wait untill a new request is ready to be processed httpCli->m_pRequestMutex->WaitForCond(COND_NEW_REQUEST); if(true == httpCli->m_bShutdownRequestThread) { httpCli->m_pRequestMutex->Release(); break; } httpCli->SendRequest(); if(NULL != httpCli->extCallbackFunc) { httpCli->extCallbackFunc(httpCli->extDataPtr); } httpCli->m_pRequestMutex->Release(); httpCli->m_bRequestCompleted = true; } return NULL; }
/* ====================================================================== Function: httpPost Purpose : Do a http post Input : hostname port url Output : true if received 200 OK Comments: - ====================================================================== */ boolean httpPost(char * host, uint16_t port, char * url) { HTTPClient http; bool ret = false; unsigned long start = millis(); // configure traged server and url http.begin(host, port, url); //http.begin("http://emoncms.org/input/post.json?node=20&apikey=2f13e4608d411d20354485f72747de7b&json={PAPP:100}"); //http.begin("emoncms.org", 80, "/input/post.json?node=20&apikey=2f13e4608d411d20354485f72747de7b&json={}"); //HTTP Debugf("http%s://%s:%d%s => ", port==443?"s":"", host, port, url); // start connection and send HTTP header int httpCode = http.GET(); if(httpCode) { // HTTP header has been send and Server response header has been handled Debug(httpCode); Debug(" "); // file found at server if(httpCode == 200) { String payload = http.getString(); Debug(payload); ret = true; } } else { DebugF("failed!"); } Debugf(" in %d ms\r\n",millis()-start); return ret; }
int main(int argc, char *argv[]) { string method, url, fileName, proxy; if(argc==5){ method = argv[1]; url = argv[2]; fileName = argv[3]; proxy = argv[4]; }else{ cerr<<"Invalid number of parameters for starting HTTPClient"<<endl <<"Usage: ./HTTPClientMain <method> <url> <localFileName> <direct/proxyaddress>"<<endl; exit(-1); } HTTPClient* httpClient = new HTTPClient(method, url, fileName, proxy); if(httpClient->run()){ cerr<<"Error in starting HTTPClient"<<endl; exit(-1); } free(httpClient); return 0; }
/******************************************************************** connect establishes a connection to the Slack RTM API ********************************************************************/ bool ArduinoSlackBot::connect() { // Step 1: Find WebSocket address via RTM API (https://api.slack.com/methods/rtm.start) HTTPClient http; String slackAddr = "https://slack.com/api/rtm.start?token="; slackAddr = String(slackAddr + slackToken); PRINTLN(slackAddr); http.begin(slackAddr.c_str(), slackSSLFingerprint); int httpCode = http.GET(); if (httpCode != HTTP_CODE_OK) { PRINTF("HTTP GET failed with code %d\n", httpCode); return false; } WiFiClient *client = http.getStreamPtr(); client->find("wss:\\/\\/"); String host = client->readStringUntil('\\'); String path = client->readStringUntil('"'); path.replace("\\/", "/"); // Step 2: Open WebSocket connection and register event handler PRINTLN("WebSocket Host=" + host + " Path=" + path); webSocket.beginSSL(host, 443, path, "", ""); webSocket.onEvent(webSocketEvent); return true; }
void ArduRPC_SensorNode::submitData() { uint16_t i; char hostname[NODE_EEPROM_API_HOSTNAME_MAX_LENGTH + 1]; uint16_t port; if(this->status != 4) { return; } if(WiFi.status() != WL_CONNECTED) { return; } /* if(connectSensorAPI() == false) { return; } */ getAPIHostnameOrDefault(&hostname[0], NODE_EEPROM_API_HOSTNAME_MAX_LENGTH); port = getAPIPortOrDefault(); HTTPClient http; String path; path.reserve(64); path = "/sensors/"; path += this->sensor_uuid; http.begin(hostname, port, path); http.addHeader("X-Sensor-Api-Key", this->sensor_key); http.addHeader("X-Sensor-Version", "1"); int code; code = http.POST(this->cache.data, this->cache.length); NODE_DEBUG_PRINT("Code "); NODE_DEBUG_PRINTLN(code); // ToDo: validate code this->status = 0; /* client.print("POST /sensors/"); client.println(this->sensor_uuid); client.print("Host: "); client.println(hostname); client.println("Connection: close"); client.print("X-Sensor-Api-Key: "); client.println(this->sensor_key); client.println("X-Sensor-Version: 1"); client.print("Content-Length: "); client.println(this->cache.length); client.println(); for(i = 0; i < this->cache.length; i++) { Serial.print((char)this->cache.data[i]); } this->status = 0; client.stop(); */ }
int main() { MBED_HOSTTEST_TIMEOUT(15); MBED_HOSTTEST_SELECT(default_auto); MBED_HOSTTEST_DESCRIPTION(HTTP client hello world); MBED_HOSTTEST_START("NET_7"); char http_request_buffer[BUFFER_SIZE + 1] = {0}; HTTPClient http; EthernetInterface eth; eth.init(); //Use DHCP eth.connect(); //GET data { bool result = true; const char *url_hello_txt = "http://developer.mbed.org/media/uploads/donatien/hello.txt"; printf("HTTP_GET: Trying to fetch page '%s'...\r\n", url_hello_txt); HTTPResult ret = http.get(url_hello_txt, http_request_buffer, BUFFER_SIZE); if (ret == HTTP_OK) { printf("HTTP_GET: Read %d chars: '%s' ... [OK]\r\n", strlen(http_request_buffer), http_request_buffer); } else { printf("HTTP_GET: Error(%d). HTTP error(%d) ... [FAIL]\r\n", ret, http.getHTTPResponseCode()); result = false; } if (result == false) { eth.disconnect(); MBED_HOSTTEST_RESULT(false); } } //POST data { bool result = true; const char *url_httpbin_post = "http://httpbin.org/post"; HTTPText text(http_request_buffer, BUFFER_SIZE); HTTPMap map; map.put("Hello", "World"); map.put("test", "1234"); printf("HTTP_POST: Trying to post data to '%s' ...\r\n", url_httpbin_post); HTTPResult ret = http.post(url_httpbin_post, map, &text); if (ret == HTTP_OK) { printf("HTTP_POST: Read %d chars ... [OK]\r\n", strlen(http_request_buffer)); printf("HTTP_POST: %s\r\n", http_request_buffer); } else { printf("HTTP_GET: Error(%d). HTTP error(%d) ... [FAIL]\r\n", ret, http.getHTTPResponseCode()); result = false; } if (result == false) { eth.disconnect(); MBED_HOSTTEST_RESULT(false); } } eth.disconnect(); MBED_HOSTTEST_RESULT(true); }
static void tcptask(void* arg) { static uint16_t port = 30000; HTTPClient* self = (HTTPClient*) arg; TCPData tcpData; for (;;) { if (xQueueReceive(self->qHandle, &tcpData, 100)) { port++; struct netconn *conn = netconn_new(NETCONN_TCP); err_t err; if (conn != NULL) { // Bind connection to the specified number os_printf("Binding port %d\n", port); err = netconn_bind(conn, NULL, port); if (err == ERR_OK) { struct ip_addr ip; ip.addr = tcpData.serverIP; os_printf("Connecting port %d\n", tcpData.serverPort); err = netconn_connect (conn, &ip, tcpData.serverPort); if (err == ERR_OK) { os_printf("Writing data!\n"); netconn_write(conn, tcpData.data, TCP_DATA_SIZE, NETCONN_COPY); struct netbuf *buf; char *data; u16_t len; uint32_t offset = 0; if ((buf = netconn_recv(conn)) != NULL) { do { netbuf_data(buf, (void**)&data, &len); if (self->rxBuffer != NULL && data != NULL) memcpy(self->rxBuffer + offset, data, len); else os_printf("HTTPClient::tcpTask self->rxBuffer or data is NULL!\n"); offset += len; os_printf("Netconn received %d bytes\n", len); } while (netbuf_next(buf) >= 0); self->onReceive(tcpData.receiveCallback, tcpData.obj, self->rxBuffer); netbuf_delete(buf); } } } } netconn_close (conn ); netconn_delete (conn ); } } vTaskDelete(NULL); }
int main(int argc, char *argv[]) { HTTPClient client = HTTPClient(ENDPOINT, 8000); client.GET(); printf("\nPress any key to exit..."); getchar(); return 0; }
// Test if we can find the MarlinClient certificate in my personal store int TestFindClientCertificate() { HTTPClient client; bool result = client.SetClientCertificateThumbprint("MY","db 34 40 64 f2 fa c2 13 18 dd 90 f5 07 fe 78 e8 1b 03 16 00"); // SUMMARY OF THE TEST // --- "---------------------------------------------- - ------ printf("Can find the Marlin client certificate in store: %s\n",result ? "OK" : "ERROR"); return result ? 0 : 1; }
bool StatisticsSender::SendStatistics(int iNoOfMessages) const { String sPage; sPage.Format(_T("/statistics/update.php?hm_version=%s&hm_messages=%d"), Application::Instance()->GetVersionNumber(), iNoOfMessages); AnsiString output; HTTPClient Client; return Client.ExecuteScript("www.hmailserver.com", sPage, output); }
/** * do a HTTP POST request, wait for it to finish * and return the content of the reply. * (requires libcurl or a command-line HTTP client) * * more documentation in oauth.h * * @param u url to query * @param p postargs to send along with the HTTP request. * @return In case of an error NULL is returned; otherwise a pointer to the * replied content from HTTP server. latter needs to be freed by caller. */ std::string oauth_http_post(const char *u, const char *p) { HTTPClient http; std::string strresult; int numread = 0; OAuthDataOut req("application/x-www-form-urlencoded", p); OAuthDataIn res(result_buffer, RESULT_BUFFER_SIZ); http.post(u, req, &res); return res.getData(); }
int httptest(CellularModem& modem, const char* apn, const char* username, const char* password) { printf("Connecting...\n"); HTTPClient http; char str[512]; modem.power(true); Thread::wait(1000); int ret = modem.connect(apn, username, password); if(ret) { printf("Could not connect\n"); return false; } //GET data printf("Trying to fetch page...\n"); ret = http.get("http://mbed.org/media/uploads/donatien/hello.txt", str, 128); if (!ret) { printf("Page fetched successfully - read %d characters\n", strlen(str)); printf("Result: %s\n", str); } else { printf("Error - ret = %d - HTTP return code = %d\n", ret, http.getHTTPResponseCode()); modem.disconnect(); return false; } //POST data HTTPMap map; HTTPText text(str, 512); map.put("Hello", "World"); map.put("test", "1234"); printf("Trying to post data...\n"); ret = http.post("http://httpbin.org/post", map, &text); if (!ret) { printf("Executed POST successfully - read %d characters\n", strlen(str)); printf("Result: %s\n", str); } else { printf("Error - ret = %d - HTTP return code = %d\n", ret, http.getHTTPResponseCode()); modem.disconnect(); return false; } modem.disconnect(); return true; }
int StatsManager::Run(void *pv) { StatsManager* sm = reinterpret_cast<StatsManager*>(pv); HTTPClient client; while (sm->run_) { std::auto_ptr<Entry> entry; { ScopedMutex mutex(sm->entry_mutex_); if (sm->entries_.empty()) { sm->busy_ = false; } else { entry.reset(new Entry(sm->entries_.front())); sm->entries_.pop(); } } if (entry.get()) { entry->parameters["platform"] = A1_DISPLAY_PLATFORM; if (dynamic_world->player_count > 1) entry->parameters["session id"] = NetSessionIdentifier(); entry->parameters["username"] = network_preferences->metaserver_login; entry->parameters["password"] = network_preferences->metaserver_password; // generate checksum uint32 checksum = 0; for (std::map<std::string, std::string>::const_iterator it = entry->parameters.begin(); it != entry->parameters.end(); ++it) { checksum += checksum_string(it->first); checksum += checksum_string(it->second); } std::ostringstream oss; oss << checksum; entry->parameters["checksum"] = oss.str(); client.Post(A1_STATSERVER_ADD_URL, entry->parameters); } else { SDL_Delay(200); } } return 0; }
void getTimeFromGoogle(String &time) { if (DEBUG) Serial << F("Check time from google") << endl; if (waitForWifi(7000) != WL_CONNECTED) return; HTTPClient http; const char *headers[1] = {"Date"}; http.begin(F("http://google.com/")); http.collectHeaders(headers, 1); int rc = http.sendRequest("HEAD"); if (rc < 0) return; time = http.header("Date"); //const char *d1 = http.header("Date").c_str(); }
int HTTPClient::clientWrite(char byte, FILE* stream) { if (stream == NULL) { return EOF; } http_stream_udata* udata = (http_stream_udata*) fdev_get_udata(stream); HTTPClient* client = udata->client; if (client->connected() == 0) { closeStream(stream); return EOF; } if (udata->encode == 0) { client->write(byte); if (client->debugCommunication) { Serial.print(byte); } } else { if (URI_ALLOWED(byte) || ((URI_RESERVED(byte) && (udata->encode & URI_ENCODE_RESERVED) == 0))) { client->write(byte); if (client->debugCommunication) { Serial.print(byte); } } else { char encoded[4] = { 0, 0, 0 }; sprintf(encoded, "%%%2x", byte); // Write only the first three bytes, not the trailing null for (char i = 0; i < 3; i++) { client->write(encoded[i]); if (client->debugCommunication) { Serial.print(encoded[i]); } } } } return 0; }
int requestConfig(bool save) { int ret = -1; HTTPClient http; // configure url sprintf(url, "http://%s:%d/iotconfig?mac=%s", iotSrv, iotPort, macStr); http.begin(url); //HTTP // start connection and send HTTP header int httpCode = http.GET(); // httpCode will be negative on error if(httpCode > 0) { // HTTP header has been send and Server response header has been handled // file found at server if(httpCode == HTTP_CODE_OK) { String payload = http.getString(); int paysize = payload.length() + 1; char json[paysize]; payload.toCharArray(json, paysize); StaticJsonBuffer<jsonSize> jsonBuffer; JsonObject& root = jsonBuffer.parseObject(json); // Test if parsing succeeds. if (!root.success()) { // parsing failed return ret; // bail out } else { // parsing successful, save file ret = root["cfgversion"]; if (save==true) { File configFile = SPIFFS.open(jsonFile, "w"); if (!configFile) { ret = -1; } root.printTo(configFile); configFile.close(); } } } } else { ret = -1; } http.end(); return ret; }
void test(void const*) { printf("VodafoneUSBModemHTTPClientTest\n"); VodafoneIOModem modem; HTTPClient http; char str[512]; int ret = modem.connect("live.vodafone.com"); if(ret) { printf("Could not connect\n"); return; }else printf("Connected!\n"); //GET data printf("Trying to fetch page...\n"); ret = http.get("http://developer.mbed.org/media/uploads/donatien/hello.txt", str, 128); if (!ret) { printf("Page fetched successfully - read %d characters\n", strlen(str)); printf("Result: %s\n", str); } else { printf("Error - ret = %d - HTTP return code = %d\n", ret, http.getHTTPResponseCode()); } //POST data HTTPMap map; HTTPText text(str, 512); map.put("Hello", "World"); map.put("test", "1234"); printf("Trying to post data...\n"); ret = http.post("http://httpbin.org/post", map, &text); if (!ret) { printf("Executed POST successfully - read %d characters\n", strlen(str)); printf("Result: %s\n", str); } else { printf("Error - ret = %d - HTTP return code = %d\n", ret, http.getHTTPResponseCode()); } modem.disconnect(); while(1) { } }
void ICACHE_FLASH_ATTR ThingSpeakClass::SendThingSpeakValues() { // if (ThingEnabled) DebugPrintln("thingspeak enabled"); else DebugPrintln("thingspeak disabled"); if (ThingEnabled == false) return; if (thingSpeakURL == "") return; DebugPrintln(thingSpeakURL); if (WiFi.status() != WL_CONNECTED) return; //check to make sure we are connected... String postStr = "api_key=" + thingWriteKey; if (HMGlobal.hmPitTemp != "U") postStr += "&field1=" + HMGlobal.hmPitTemp; if (HMGlobal.hmFood1 != "U") postStr += "&field2=" + HMGlobal.hmFood1; if (HMGlobal.hmFood2 != "U") postStr += "&field3=" + HMGlobal.hmFood2; if (HMGlobal.hmAmbient != "U") postStr += "&field4=" + HMGlobal.hmAmbient; if (HMGlobal.hmFanMovAvg != "U") postStr += "&field5=" + HMGlobal.hmFanMovAvg; if (HMGlobal.hmFan != "U") postStr += "&field6=" + HMGlobal.hmFan; if (HMGlobal.hmSetPoint != "U") postStr += "&field7=" + HMGlobal.hmSetPoint; if (HMGlobal.hmLidOpenCountdown != "U") postStr += "&field8=" + HMGlobal.hmLidOpenCountdown; if (inAlarm) //if alarm was triggered we send on next msg { postStr += "&status=" + MyWebServer.urlencode(MyWebServer.CurTimeString() + " " + AlarmInfo); AlarmInfo = ""; inAlarm = false; } HTTPClient http; DebugPrintln("http://" + thingSpeakURL + "/update"); http.begin("http://" + thingSpeakURL + "/update"); int httpCode = http.POST(postStr); // httpCode will be negative on error if (httpCode > 0) { if (httpCode == HTTP_CODE_OK) { } } else { DebugPrintln("[HTTP] POST... failed, error: " + http.errorToString(httpCode)); } http.end(); DebugPrintln("sending thingspeak stuffs"); }
void ControlTopology(sp_string topology_id, sp_int32 port, bool activate) { EventLoopImpl ss; AsyncDNS dns(&ss); HTTPClient* client = new HTTPClient(&ss, &dns); HTTPKeyValuePairs kvs; kvs.push_back(make_pair("topologyid", topology_id)); sp_string requesturl = activate ? "/activate" : "/deactivate"; OutgoingHTTPRequest* request = new OutgoingHTTPRequest(LOCALHOST, port, requesturl, BaseHTTPRequest::GET, kvs); auto cb = [client](IncomingHTTPResponse* response) { ControlTopologyDone(client, response); }; if (client->SendRequest(request, std::move(cb)) != SP_OK) { FAIL() << "Unable to send the request\n"; } ss.loop(); }
void CustomURL_Plugin::sndGENIOT(const char *line) { char str[140], str2[150]; strcpy(str, PropertyList.readProperty(EE_GENIOT_PATH)); if (strstr(str, "thingspeak")) { strcat(str, "&field2=%d"); sprintf(str2, str, &line[7], millis()/60000L); } else { sprintf(str2, str, &line[7]); } SERIAL_PORT << F("Sending to URL: \"") << str2 << "\"" << endl; HTTPClient http; http.begin(str2); //addHCPIOTHeaders(&http, token); int rc = AT_FW_Plugin::processResponseCodeATFW(&http, http.GET()); //SERIAL_PORT << "Result: " << http.errorToString(rc).c_str(); }
Handle<Value> loadHTTPClient(const v8::Arguments& args) { if(!args.IsConstructCall()) { return v8::ThrowException(String::New("Cannot call constructor as a function")); } Shell *shell = Shell::Instance(); Context::Scope context_scope(shell->globalContext); HandleScope scope; string argument; HTTPClient *newHTTPClient; if (args.Length() == 1) { argument = *String::Utf8Value(args[0]); newHTTPClient = new HTTPClient(argument); } else { newHTTPClient = new HTTPClient(); } return(scope.Close(newHTTPClient->registerObject())); }
bool Language::Download() { AnsiString output; HTTPClient client; bool result = client.ExecuteScript("www.hmailserver.com", "/devnet/translation_getlanguage.php?language=" + m_sName, output); String unicodeString = output; Unicode::MultiByteToWide(output, unicodeString); FileUtilities::WriteToFile("C:\\test.txt", unicodeString, true); return result; }
int main(int argc, char** argv) { if (argc < 3) return usage(argc, argv); const long timeout = lexicalCast<long>(argv[1]); SocketModule Module; try { for (int args = 2; args < argc; ++args) { std::string targetResource(argv[args]); HTTPClient<> client; client.setKeepAliveTime(300); client.setTimeout(timeout, 1); client.setUserAgent("Mozilla/4.0 (compatible; MSIE 6.0; " "Windows NT 5.1; SV1; .NET CLR 1.0.3705; " ".NET CLR 1.1.4322)"); client.setAcceptEncoding(""); client.addAcceptLanguage("ja"); client.addAcceptLanguage("en"); HTTPResult<> result = client.getResource(targetResource.c_str()); std::cout << "headers: " << result.getResponseHeaders().toString() << std::endl; std::vector<unsigned char> resource = result.getResource(); std::ofstream ofs("savefile.html", std::ios::out | std::ios::binary | std::ios::trunc); std::vector<unsigned char>::const_iterator itor = resource.begin(); while (itor != resource.end()) ofs << *itor++; ofs.close(); } } catch (ResponseError& e) { std::cout << " raise exception. reason: " << e.what() << std::endl; } catch (ConnectionClosedException& /*e*/) { std::cout << "connection closed by forign host." << std::endl; } catch (SocketException& /*e*/) { std::cout << "target server is not found. "; } catch (std::exception& e) { std::cout << "raise exception. reason: " << e.what() << std::endl; } return 0; }
int Update::Thread() { std::ostringstream url; url << "http://" << A1_UPDATE_HOST << "/update_check/" << A1_UPDATE_PLATFORM << ".php"; HTTPClient fetcher; if (!fetcher.Get(url.str())) { m_status = UpdateCheckFailed; return 1; } boost::char_separator<char> sep("\r\n"); boost::tokenizer<boost::char_separator<char> > tokens(fetcher.Response(), sep); for (boost::tokenizer<boost::char_separator<char> >::iterator it = tokens.begin(); it != tokens.end(); ++it) { if (boost::algorithm::starts_with(*it, "A1_DATE_VERSION: ")) { m_new_date_version = it->substr(strlen("A1_DATE_VERSION: ")); } else if (boost::algorithm::starts_with(*it, "A1_DISPLAY_VERSION: ")) { m_new_display_version = it->substr(strlen("A1_DISPLAY_VERSION: ")); } } if (m_new_date_version.size()) { m_status = m_new_date_version.compare(A1_DATE_VERSION) > 0 ? UpdateAvailable : NoUpdateAvailable; return 0; } else { m_status = UpdateCheckFailed; return 5; } }
Json::Value make_rpc_req(Json::Value query, bool logit,unsigned char host,int timeout) { HTTPClient cl; cl.rh["Authorization"] = hosts[host].aut; cl.rh["Connection"] = "close"; Json::FastWriter writer; cl.pr["_full_post"] = writer.write(query); if (logit) { FILE *fd = fopen(".rpc.log", "w"); // log only 1 transaction if (fd) { fprintf(fd, "COMPLETE RPC REQUEST:\n%s\nEND OF REQUEST\n", cl.pr["_full_post"].c_str()); fclose(fd); } } if(timeout){ signal(SIGALRM,connect_alarm); alarm(timeout); cl.request(hosts[host].url,true); alarm(0);} else{ cl.request(hosts[host].url,true);} if (!cl.isOK()) { return Json::Value(); } std::string ans; while (cl.peek() != EOF) { unsigned to_r = cl.rdbuf()->in_avail(); if (to_r == 0) break; if (to_r > 4000) to_r = 4000; char tbuf[to_r+2]; cl.read(tbuf,to_r); ans += std::string(tbuf, to_r); } if (logit) { FILE *fd = fopen(".rpc.log", "a"); if (fd) { fprintf(fd, "COMPLETE RPC ANSWER:\n%s\nEND OF ANSWER\n", ans.c_str()); fclose(fd); } } cl.disconnect(); Json::Reader reader; Json::Value answ; if (!reader.parse(ans, answ)) return false; if (answ.type() != Json::objectValue) return false; answ = answ["result"]; if (answ.type() != Json::objectValue) return false; return answ; }
bool SendMailSms::FinalizeConnection() { HTTPClient http; ESP.wdtDisable(); TRACE2("Open URL: ",m_Data); if ( !http.begin(m_Data) ) { TRACE2("Error opening URL: ",m_Data); ESP.wdtEnable(10000); return false; } int httpCode = http.GET(); TRACE2("HTTP Code: ",httpCode); bool bRvl = false; if (httpCode == HTTP_CODE_OK) { String payload = http.getString(); TRACE(payload); if (payload.indexOf("{\"success\":true")>=0) bRvl = true; } http.end(); ESP.wdtEnable(10000); return bRvl; }
int main(int argc, char *argv[]) { string method, url, fileName, proxy; if (argc == 5) { method = argv[1]; url = argv[2]; fileName = argv[3]; proxy = argv[4]; } else { cerr << "Invalid number of parameters for starting HTTPClient" << endl << "Usage: ./HTTPClientMain <method> <url> <localFileName> <direct/proxyaddress>" << endl; exit(-1); } HTTPClient* httpClient = new HTTPClient(method, url, fileName, proxy); //in case of lack of memory if(!httpClient) { cerr <<"Can not allocate memory to HTTPClient!" <<endl; return -1; } if (httpClient->run()) { cerr << "Error in starting HTTPClient" << endl; delete httpClient; return -2; } delete httpClient; return 0; }
void http_access_test() { HTTPClient* httpClient = new HTTPClient(); HTTPHeader* httpHeader = new HTTPHeader(); httpHeader->insert( std::string("Content-Type"), std::string("application/x-www-form-urlencoded") ); httpHeader->insert( std::string("Connection"), std::string("close") ); httpClient->get( new std::string("http://www.ex-studio.info/"), httpHeader ); int status_code = httpClient->status_code(); std::cout << "Status code: " << status_code << std::endl; if(status_code != 200) { delete httpHeader; delete httpClient; return; } HTTPHeader* recvHeader = httpClient->header(); std::string* recvBody = httpClient->body(); std::cout << "Date is " << recvHeader->get("Date") << std::endl; std::cout << "body: " << *recvBody << std::endl; delete httpHeader; delete httpClient; return; }
int main(int argc, char **argv) { if (argc < 4) { printf("usage: httpclient <host> <port> <url> [keep-alive]\n"); return 1; } auto engine = std::make_shared<vespalib::NullCryptoEngine>(); HTTPClient *client; ssize_t len; if(argc == 4) { client = new HTTPClient(engine, argv[1], atoi(argv[2]), false, true); } else { client = new HTTPClient(engine, argv[1], atoi(argv[2]), true, true); } std::ostream * output = & std::cout; if ((len = client->Fetch(argv[3], output).ResultSize()) >= 0) { printf("SUCCESS!\n"); printf("LENGTH: %ld\n", len); } else { printf("ERROR: could not fetch URL content.\n"); } if ((len = client->Fetch(argv[3], output).ResultSize()) >= 0) { printf("SUCCESS!\n"); printf("LENGTH: %ld\n", len); } else { printf("ERROR: could not fetch URL content.\n"); } std::this_thread::sleep_for(std::chrono::seconds(20)); if ((len = client->Fetch(argv[3], output).ResultSize()) >= 0) { printf("SUCCESS!\n"); printf("LENGTH: %ld\n", len); } else { printf("ERROR: could not fetch URL content.\n"); } if ((len = client->Fetch(argv[3], output).ResultSize()) >= 0) { printf("SUCCESS!\n"); printf("LENGTH: %ld\n", len); } else { printf("ERROR: could not fetch URL content.\n"); } printf("REUSE COUNT: %zu\n", client->GetReuseCount()); return 0; }
String getHTTPFile(String url) { HTTPClient http; String payload; // Serial << "Retriving HTTP: " << url << endl; http.begin(url); //HTTP int httpCode = http.GET(); if(httpCode > 0) { if (DEBUG) Serial << F("[HTTP] GET... code:") << httpCode << endl; if(httpCode == HTTP_CODE_OK) payload = http.getString(); } else { if (DEBUG) Serial << F("[HTTP] GET... failed, error:") << http.errorToString(httpCode).c_str() << endl; } http.end(); return payload; }