简体   繁体   English

使用C ++将POST请求发送到Apache Web服务器

[英]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. 我正在尝试将一些数据从C ++应用程序发送到同一台机器上的apache服务器。 I wrote some c++ code to send a POST request to the apache server. 我写了一些C ++代码将POST请求发送到apache服务器。 The PHP script on the index.php page should collect the data and output them on the web page. index.php页面上的PHP脚本应收集数据并将其输出到网页上。

My C++ code: 我的C ++代码:

      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_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 我在index.php上的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. 我确定POST请求的格式正确。 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. 要从Web服务器获取答复,您应该尝试从套接字读取而不是在发送/写入后立即将其关闭。

I would also suggest you to get some more confidence with network programmin. 我还建议您对Network Programmin更有信心。 Here you get an evergreen read: 在这里,您会得到常绿的读物:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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