client_example.md 1.09 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
---
title: HTTP client example
---

To create an HTTP client, follow this pattern:

1. Create an outbound connection by calling `mg_connect_http()`
2. Create an event handler function that handles `MG_EV_HTTP_REPLY` event

Here's an example of the simplest HTTP client.
Error checking is omitted for the sake of clarity:

```c
#include "mongoose.h"

static const char *url = "http://www.google.com";
static int exit_flag = 0;

static void ev_handler(struct mg_connection *c, int ev, void *p) {
  if (ev == MG_EV_HTTP_REPLY) {
Yiming Sun's avatar
Yiming Sun committed
21
    struct http_message *hm = (struct http_message *)p;
22
    c->flags |= MG_F_CLOSE_IMMEDIATELY;
Yiming Sun's avatar
Yiming Sun committed
23
    fwrite(hm->message.p, 1, (int)hm->message.len, stdout);
24 25
    putchar('\n');
    exit_flag = 1;
26 27 28
  } else if (ev == MG_EV_CLOSE) {
    exit_flag = 1;
  };
29 30 31 32 33 34
}

int main(void) {
  struct mg_mgr mgr;

  mg_mgr_init(&mgr, NULL);
Yiming Sun's avatar
Yiming Sun committed
35
  mg_connect_http(&mgr, ev_handler, url, NULL, NULL);
36 37 38 39 40 41 42 43 44 45 46


  while (exit_flag == 0) {
    mg_mgr_poll(&mgr, 1000);
  }
  mg_mgr_free(&mgr);

  return 0;
}
```

47
See full source code at [HTTP client example](https://github.com/cesanta/mongoose/tree/master/examples/http_client).