handle the httpbin API image endpoint
This commit is contained in:
1 parent
4a1eb87532
commit
fdb050633f
2 files changed
+44
-9
No files matched your search
+1
-1
@@ -1,5 +1,5 @@
|
||||
cmake_minimum_required(VERSION 3.10)
|
||||
project(MbedTLS Integration Example)
|
||||
project("MbedTLS Integration Example")
|
||||
|
||||
add_subdirectory(mbedtls)
|
||||
|
||||
|
||||
+43
-8
@@ -11,7 +11,8 @@
|
||||
|
||||
#define SERVER_PORT "443"
|
||||
#define SERVER_NAME "httpbin.org"
|
||||
#define GET_REQUEST "GET /get HTTP/1.1\r\nHost: httpbin.org\r\nConnection: close\r\n\r\n"
|
||||
// #define GET_REQUEST "GET /get HTTP/1.1\r\nHost: httpbin.org\r\nConnection: close\r\n\r\n"
|
||||
#define GET_REQUEST "GET /image HTTP/1.1\r\nHost: httpbin.org\r\naccept: image/webp\r\n\r\n"
|
||||
#define DEBUG_LEVEL 0
|
||||
|
||||
static void my_debug(void *ctx, int level,
|
||||
@@ -137,17 +138,51 @@ int main(void) {
|
||||
|
||||
mbedtls_printf("Receiving response:\n\n");
|
||||
|
||||
int response_received = 0;
|
||||
while ((bytes_read = mbedtls_ssl_read(&ssl, buf, sizeof(buf) - 1)) > 0) {
|
||||
buf[bytes_read] = '\0';
|
||||
mbedtls_printf("%s", (char *)buf);
|
||||
response_received = 1;
|
||||
FILE *img_file = fopen("image.webp", "wb");
|
||||
if (img_file == NULL) {
|
||||
mbedtls_printf(" failed\n ! Could not create image file\n\n");
|
||||
goto exit;
|
||||
}
|
||||
|
||||
int skip_headers = 0;
|
||||
int res_recv = 0;
|
||||
|
||||
while ((bytes_read = mbedtls_ssl_read(&ssl, buf, sizeof(buf) - 1)) > 0) {
|
||||
unsigned char *data_to_write = buf;
|
||||
size_t data_len = bytes_read;
|
||||
|
||||
if (!skip_headers) {
|
||||
unsigned char *header_end = (unsigned char *)strstr((const char *)buf, "\r\n\r\n");
|
||||
|
||||
if (header_end != NULL) {
|
||||
data_to_write = header_end + 4; // +4 to skip the "\r\n\r\n"
|
||||
data_len = bytes_read - (data_to_write - buf);
|
||||
skip_headers = 1;
|
||||
|
||||
mbedtls_printf("Headers skipped, image data starts (%zu bytes in first chunk)\n", data_len);
|
||||
} else {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
size_t written = fwrite(data_to_write, 1, data_len, img_file);
|
||||
if (written != data_len) {
|
||||
mbedtls_printf(" failed\n ! Could not write to image file\n\n");
|
||||
fclose(img_file);
|
||||
goto exit;
|
||||
}
|
||||
|
||||
res_recv = 1;
|
||||
}
|
||||
|
||||
fclose(img_file);
|
||||
|
||||
if (bytes_read < 0) {
|
||||
if (bytes_read == MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY) {
|
||||
if (!response_received) {
|
||||
mbedtls_printf("\n (Connection closed by server)\n");
|
||||
if (res_recv) {
|
||||
mbedtls_printf("\nImage saved to image.webp\n");
|
||||
} else {
|
||||
mbedtls_printf("\n(Connection closed by server)\n");
|
||||
}
|
||||
} else {
|
||||
unsigned char error_buffer[256];
|
||||
|
||||
Reference in new issue
Block a user