繁体   English   中英

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

[英]Sending POST request with C++ to Apache Webserver

我正在尝试将一些数据从C ++应用程序发送到同一台机器上的apache服务器。 我写了一些C ++代码将POST请求发送到apache服务器。 index.php页面上的PHP脚本应收集数据并将其输出到网页上。

我的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;
        }

用我的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";

我在index.php上的PHP代码

<?php
print_r($_POST);
?>

可悲的是,我在索引页面上看不到任何内容。 我确定POST请求的格式正确。 您能帮我解决问题吗?

您希望在哪里看到东西? 要从Web服务器获取答复,您应该尝试从套接字读取而不是在发送/写入后立即将其关闭。

我还建议您对Network Programmin更有信心。 在这里,您会得到常绿的读物:

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

暂无
暂无

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

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