C ++ WebRequest响应

时间:2015-10-03 16:32:46

标签: c++ sockets http response webrequest

我正在编写一个程序,用于在C ++中为url创建WebRequest。这是我的代码:

void CreateRequest()
{
    WSADATA wsaData;
    if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0) {
        return;
    }
    SOCKET Socket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
    struct hostent *host;
    host = gethostbyname("www.website.net");
    SOCKADDR_IN SockAddr;
    SockAddr.sin_port = htons(80);
    SockAddr.sin_family = AF_INET;
    SockAddr.sin_addr.s_addr = *((unsigned long*)host->h_addr);
    if (connect(Socket, (SOCKADDR*)(&SockAddr), sizeof(SockAddr)) != 0){
        return;
    }
    const char link[] = "www.website.net";

    char Link[100] = "";
    strcat(Link, "GET /File.php?Test=");
    strcat(Link, "test");
    strcat(Link, " HTTP/1.1\r\nHost: www.website.net \r\nConnection: close\r\n\r\n");


    send(Socket, Link, strlen(Link), 0);

    char buffer[10000];
    int nDataLength;
    while ((nDataLength = recv(Socket, buffer, 10000, 0)) > 0){
        int i = 0;
        while (buffer[i] >= 32 || buffer[i] == '\n' || buffer[i] == '\r') {
            cout << buffer[i];
            i += 1;
        }
    }
    closesocket(Socket);
    WSACleanup();
}

结果如下:

enter image description here

我想要做的只是获取“访问被拒绝”,以便我可以从我的代码中检查请求状态。

1 个答案:

答案 0 :(得分:0)

strcat(Link, " HTTP/1.1\r\nHost: www.website.net \r\nConnection: close\r\n\r\n")

主机名和\ r \ n之间有一个额外的空格。尝试删除它,看起来像:

strcat(Link, " HTTP/1.1\r\nHost: www.website.net\r\nConnection: close\r\n\r\n")

编辑:

完全有可能HTTP级别的所有内容都正常工作,但服务器上的PHP文件正在生成&#34; Access Denied&#34;信息。你有控制PHP文件吗?