Untitled

mail@pastecode.io avatar
unknown
plain_text
7 months ago
2.0 kB
3
Indexable
Never
#include <WiFi.h>
#include <HTTPClient.h>

const char* ssid = "your-ssid";
const char* password = "your-password";
const char* server = "your-server.com";
const int port = 80;
const char* endpoint = "/your-api-endpoint";
const char* username = "your-username";
const char* userpassword = "your-password";

void setup() {
  Serial.begin(115200);

  // Connect to Wi-Fi
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(1000);
    Serial.println("Connecting to WiFi...");
  }
  Serial.println("Connected to WiFi");
}

void loop() {
  HTTPClient http;

  // Construct the URL
  String url = "http://" + String(server) + ":" + String(port) + String(endpoint);

  // Start the POST request
  http.begin(url);

  // Add headers
  http.addHeader("Content-Type", "application/x-www-form-urlencoded");
  http.addHeader("Authorization", "Basic " + base64Encode(String(username) + ":" + String(userpassword)));

  // Make the request
  int httpCode = http.POST("");

  // Check the response
  if (httpCode > 0) {
    Serial.printf("HTTP status code: %d\n", httpCode);
    String payload = http.getString();
    Serial.println("Response payload: " + payload);
  } else {
    Serial.printf("HTTP request failed, error: %s\n", http.errorToString(httpCode).c_str());
  }

  // End the request
  http.end();

  delay(5000);  // Delay for 5 seconds before the next request
}

String base64Encode(String source) {
  char base64Chars[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  String encoded = "";
  int val = 0, valb = -6;

  for (uint8_t c : source) {
    val = (val << 8) + c;
    valb += 8;
    while (valb >= 0) {
      encoded += base64Chars[(val >> valb) & 0x3F];
      valb -= 6;
    }
  }

  if (valb > -6) encoded += base64Chars[((val << 8) >> (valb + 8)) & 0x3F];
  while (encoded.length() % 4) encoded += '=';

  return encoded;
}
Leave a Comment