我想使用C ++中的Winsock通过GET请求在Google上进行搜索查询。
现在,响应具有脚本和样式,但没有任何实际搜索结果。最终目标是能够从Google检索到PDF的链接。
例如以编程方式进行这样的搜索查询:www.google.com/search?as_q=Computer+Networking&as_filetype=pdf
这是出于学习目的,我想坚持使用Winsock,而不是其他任何库。
#include "pch.h"
#define _WINSOCK_DEPRECATED_NO_WARNINGS
#include <WinSock2.h>
#include <WS2tcpip.h>
#pragma comment(lib, "Ws2_32.lib")
#include <string>
#include <fstream>
#include <iostream>
int error(std::string message);
static int err = 0;
static char buffer[0xFFFFFFF];
int main()
{
std::string url = "www.google.com";
std::string query = "Computer+Networking";
// Store source code response here
std::string source;
WSAData wsaData;
SOCKET Socket = INVALID_SOCKET;
SOCKADDR_IN SockAddr;
struct hostent *host;
std::string GET = "";
GET += "GET /search?as_q=" + query + "&as_filetype=pdf HTTP/1.1\r\n";
GET += "Accept-Encoding: gzip, deflate, br";
GET += "Accept-Language: en-US, en; q=0.9, nb; q=0.1";
GET += "Cache-Control: no-cache";
GET += "Content-Type: text/plain; charset=UTF-8";
GET += "Host: " + url + "\r\n";
GET += "Connection: close\r\n\r\n";
err = WSAStartup(MAKEWORD(2, 2), &wsaData);
if (err)
return error("WSAStartup");
Socket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (Socket == INVALID_SOCKET)
return error("Invalid socket.");
host = gethostbyname(url.c_str());
SockAddr.sin_port = htons(80);
SockAddr.sin_family = AF_INET;
SockAddr.sin_addr.s_addr = *((unsigned long*)host->h_addr);
err = connect(Socket, (SOCKADDR*)(&SockAddr), sizeof(SockAddr));
if (err)
return error("Connection failed.");
send(Socket, GET.c_str(), strlen(GET.c_str()), NULL);
int i = 0;
int nDataLength;
while ((nDataLength = recv(Socket, buffer, 0xFFFFFFF, NULL)) > 0)
{
while (buffer[i] >= 32 || buffer[i] == '\n' || buffer[i] == '\r')
{
source += buffer[i];
i++;
}
}
closesocket(Socket);
WSACleanup();
std::cout << source << std::endl;
}
int error(std::string message)
{
std::cout << "ERROR: " << message << std::endl;
return -1;
}