简体   繁体   中英

Sending POST request with C++ to Apache Webserver

I'm trying to send some data from a c++ application to the apache server on the same machine. I wrote some c++ code to send a POST request to the apache server. The PHP script on the index.php page should collect the data and output them on the web page.

My C++ code:

      void send_post()
       {
        portno = 80;
        sockfd = socket(AF_INET, SOCK_STREAM, 0);
        if (sockfd < 0)
        {
            cout << "ERROR opening socket" << endl;
        }
        else {cout << "Socket opened -> ";}

        server = gethostbyname("localhost");
        if (server == NULL)
        {
            cout << "ERROR, no such host" << endl;
            exit(0);
        }
        bzero((char *) &serv_addr, sizeof(serv_addr));
        serv_addr.sin_family = AF_INET;
        bcopy((char *)server->h_addr, (char*)&serv_addr.sin_addr.s_addr,server->h_length);
        serv_addr.sin_port = htons(portno);

        if (connect(sockfd,(struct sockaddr *) &serv_addr,sizeof(serv_addr)) < 0)
        {
        cout << "ERROR connecting" << endl;
        }
        else {cout << "Connected -> ";}
        bzero(upcbuffer,512);
        sprintf(upcbuffer, "%s", post_req.c_str());
        z = write(sockfd,upcbuffer,strlen(upcbuffer));
        if (z < 0)
        {
        cout << "ERROR writing to socket";
        }
        else {cout << "Wrote successfully to socket" << endl;}
        close(sockfd);
        cout << "Socket closed now" << endl;
        }

With my post_req string:

post_req = "POST /index.php HTTP/1.1\r\nHost: localhost\r\nContent-Type: application/x-www-form-urlencoded\r\nContent-Length: 8\r\n\r\ntesttest\r\n";

My PHP code on index.php

<?php
print_r($_POST);
?>

Sadly I can't see anything on the index page. I'm sure that the POST request is well formatted. Could you help me to fix the problem ?

Where do you expect to see something? To get the reply from the web server you should attempt to read from the socket instead of close it immediately after send/write.

I would also suggest you to get some more confidence with network programmin. Here you get an evergreen read:

http://beej.us/guide/bgnet/output/html/multipage/index.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM