Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / C

Capture Incoming HTTP Requests to the Web Server

0.00/5 (No votes)
27 Nov 2014CPOL1 min read 17.5K  
How to handle post data coming inside an HTTP POST request

Introduction

Few days ago, I had a problem in my CGI application where I must capture the data inside the HTTP POST request coming to the application. The post data are XML data that I must parse and process. In this tip/trick, I will share the idea and the solution I found.

Background

There are few things at least you must know, types of HTTP requests and the HTTP request format, so I suggest you check this detailed article on Wikipedia on the HTTP protocol. I also suggest you review some CGI concepts especially the environment variables.

Using the Code

The idea behind the solution is the CGI environment variables, especially the CONTENT_LENGTH variable. This variable indicates the number of bytes (size) of the data passed within a POST HTTP request.

Any C/C++ application has standard input and output, so when you run the application as CGI, the standard input/output will be through server. So to read the post data, you read the value of CONTENT_LENGTH and then read from stdin. Here is how it is done:

C++
char* len_ = getenv("CONTENT_LENGTH");
if(len_)
{
    long int len = strtol(len_, NULL, 10);
    cout << "LENGTH = " << len << endl;
    char* postdata = (char*)malloc(len + 1);
    if (!postdata) { exit(EXIT_FAILURE); }
    fgets(postdata, len + 1, stdin);
    cout << "DATA = " << postdata << endl;
    free(postdata);
}
else
{
    // No CONTENT_LENGTH, therefore no post data available.
}

Points of Interest

Always check for the value of CONTENT_LENGTH, if no data is available within the request, it becomes null. And always allocate extra location for the null terminator.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)