mongoose/examples/http-client/main.c

57 lines
2.2 KiB
C
Raw Normal View History

2021-01-30 21:03:11 +08:00
// Copyright (c) 2021 Cesanta Software Limited
2020-12-10 21:26:05 +08:00
// All rights reserved
//
2020-12-18 22:29:30 +08:00
// Example HTTP client. Connect to `s_url`, send request, wait for a response,
// print the response and exit.
2021-01-30 21:03:11 +08:00
// You can change `s_url` from the command line by executing: ./example YOUR_URL
2020-12-10 21:26:05 +08:00
//
// To enable SSL/TLS for this client, build it like this:
2021-01-30 21:03:11 +08:00
// make MBEDTLS=/path/to/your/mbedtls/installation
// make OPENSSL=/path/to/your/openssl/installation
2020-12-10 21:26:05 +08:00
#include "mongoose.h"
2021-01-30 21:03:11 +08:00
// The very first web page in history. You can replace it from command line
2021-03-24 23:49:35 +08:00
static const char *s_url = "http://info.cern.ch//foo";
2020-12-18 22:29:30 +08:00
2020-12-10 21:26:05 +08:00
// Print HTTP response and signal that we're done
static void fn(struct mg_connection *c, int ev, void *ev_data, void *fn_data) {
2020-12-18 22:29:30 +08:00
if (ev == MG_EV_CONNECT) {
2021-01-30 21:03:11 +08:00
// Connected to server. Extract host name from URL
2020-12-25 00:52:58 +08:00
struct mg_str host = mg_url_host(s_url);
2021-01-30 21:03:11 +08:00
// If s_url is https://, tell client connection to use TLS
2020-12-18 22:29:30 +08:00
if (mg_url_is_ssl(s_url)) {
2021-02-13 18:45:27 +08:00
struct mg_tls_opts opts = {.ca = "ca.pem", .srvname = host};
2020-12-18 22:29:30 +08:00
mg_tls_init(c, &opts);
}
2021-01-30 21:03:11 +08:00
2020-12-18 22:29:30 +08:00
// Send request
2021-01-30 21:03:11 +08:00
mg_printf(c,
"GET %s HTTP/1.0\r\n"
"Host: %.*s\r\n"
"\r\n",
mg_url_uri(s_url), (int) host.len, host.ptr);
2020-12-18 22:29:30 +08:00
} else if (ev == MG_EV_HTTP_MSG) {
// Response is received. Print it
2020-12-10 21:26:05 +08:00
struct mg_http_message *hm = (struct mg_http_message *) ev_data;
printf("%.*s", (int) hm->message.len, hm->message.ptr);
2020-12-18 22:29:30 +08:00
c->is_closing = 1; // Tell mongoose to close this connection
*(bool *) fn_data = true; // Tell event loop to stop
2021-01-30 21:03:11 +08:00
} else if (ev == MG_EV_ERROR) {
*(bool *) fn_data = true; // Error, tell event loop to stop
2020-12-10 21:26:05 +08:00
}
}
2021-01-30 21:03:11 +08:00
int main(int argc, char *argv[]) {
2020-12-18 22:29:30 +08:00
struct mg_mgr mgr; // Event manager
bool done = false; // Event handler flips it to true
2021-01-30 21:03:11 +08:00
if (argc > 1) s_url = argv[1]; // Use URL from command line
2020-12-18 22:29:30 +08:00
mg_log_set("3"); // Set to 0 to disable debug
mg_mgr_init(&mgr); // Initialise event manager
mg_http_connect(&mgr, s_url, fn, &done); // Create client connection
while (!done) mg_mgr_poll(&mgr, 1000); // Infinite event loop
mg_mgr_free(&mgr); // Free resources
2020-12-10 21:26:05 +08:00
return 0;
}