Important changes to repositories hosted on mbed.com
Mbed hosted mercurial repositories are deprecated and are due to be permanently deleted in July 2026.
To keep a copy of this software download the repository Zip archive or clone locally using Mercurial.
It is also possible to export all your personal repositories from the account settings page.
Dependencies: W5500Interface easy-connect mbed-http
Fork of http-webserver-example by
main.cpp
00001 #include "mbed.h" 00002 #include "easy-connect.h" 00003 #include "http_server.h" 00004 #include "http_response_builder.h" 00005 00006 //Serial pc(USBTX, USBRX); 00007 //DigitalOut led(D1); 00008 //confict with W5500 SPI CS pin, so D1 pin can't use for this example. 00009 00010 // Requests come in here 00011 void request_handler(ParsedHttpRequest* request, TCPSocket* socket) { 00012 00013 printf("Request came in: %s %s\n", http_method_str(request->get_method()), request->get_url().c_str()); 00014 00015 if (request->get_method() == HTTP_GET && request->get_url() == "/") { 00016 HttpResponseBuilder builder(200); 00017 builder.set_header("Content-Type", "text/html; charset=utf-8"); 00018 00019 char response[] = "<html><head><title>Hello from mbed</title></head>" 00020 "<body>" 00021 "<h1>mbed webserver</h1>" 00022 "<button id=\"toggle\">Toggle LED</button>" 00023 "<script>document.querySelector('#toggle').onclick = function() {" 00024 "var x = new XMLHttpRequest(); x.open('POST', '/toggle'); x.send();" 00025 "}</script>" 00026 "</body></html>"; 00027 00028 builder.send(socket, response, sizeof(response) - 1); 00029 } 00030 else if (request->get_method() == HTTP_POST && request->get_url() == "/toggle") { 00031 printf("toggle LED called\n"); 00032 //led = !led; 00033 HttpResponseBuilder builder(200); 00034 builder.send(socket, NULL, 0); 00035 } 00036 else { 00037 HttpResponseBuilder builder(404); 00038 builder.send(socket, NULL, 0); 00039 } 00040 } 00041 00042 int main() { 00043 // pc.baud(115200); 00044 00045 // Connect to the network (see mbed_app.json for the connectivity method used) 00046 NetworkInterface* network = easy_connect(true); 00047 if (!network) { 00048 printf("Cannot connect to the network, see serial output\n"); 00049 return 1; 00050 } 00051 00052 HttpServer server(network); 00053 nsapi_error_t res = server.start(8080, &request_handler); 00054 00055 if (res == NSAPI_ERROR_OK) { 00056 printf("Server is listening at http://%s:8080\n", network->get_ip_address()); 00057 } 00058 else { 00059 printf("Server could not be started... %d\n", res); 00060 } 00061 00062 wait(osWaitForever); 00063 00064 }
Generated on Wed Jul 13 2022 03:01:02 by
1.7.2
