gpt4 book ai didi

c++ - 对维基百科的 HTTP 请求

转载 作者:行者123 更新时间:2023-11-28 05:45:40 31 4
gpt4 key购买 nike

我正在尝试通过套接字编程和 C++ 脚本访问维基百科页面。我可以访问服务器,但收到 404 错误,通知我请求的 URL 不存在。只需在浏览器中输入相同的 URL 即可。

这是网址:http://en.wikipedia.org/wiki/Hypertext_Transfer_Protocol

这是 C++ 脚本:

#include <iostream>
#include <sys/socket.h>
#include <resolv.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <cstring>

using namespace std;

int main()
{
int s, error;
char length[10];
length[0]=0;

struct sockaddr_in addr;

if((s = socket(AF_INET,SOCK_STREAM,0))<0)
{
cout<<"Error 01: creating socket failed!\n";
close(s);
return 1;
}

addr.sin_family = AF_INET;
addr.sin_port = htons(80);
inet_aton("204.27.61.92",&addr.sin_addr);

error = connect(s,(sockaddr*)&addr,sizeof(addr));
if(error!=0)
{
cout<<"Error 02: conecting to server failed!\n";
close(s);
return 1;
}

char msg[]="GET /wiki/Hypertext_Transfer_Protocol HTTP/1.1\nHOST: en.wikipedia.org\n\n"

int leng = send(s, msg, sizeof(msg), 0);

if(leng == -1)
cout<<"There is a problem!"<<endl;

send(s,msg,sizeof(msg),0);

char answ[1024];

ssize_t len;
while((len = recv(s, answ, 1024, 0)) > 0)
{
cout.write(answ, len);
}
cout << endl;

if(len < 0)
{
cout<<"Error!"<<endl;
}

close(s);

return 0;
}

该脚本总体上运行良好。交换线路

char msg[]="GET /wiki/Hypertext_Transfer_Protocol HTTP/1.1\nHOST: en.wikipedia.org\n\n";

char msg[] = "GET /beej/inet_ntoaman.html http/1.1\nHOST: retran.com\n\n";

无错误地检索请求的网站。我在这里错过了什么?为什么该脚本不适用于维基百科?

谢谢

最佳答案

  1. 您要连接的 IP 地址不是维基百科的。
  2. 您的代码声称符合 HTTP 1.1 但不支持分块编码。
  3. 您出于某种原因发送了两次请求。
  4. 您似乎希望服务器在向您发送数据后关闭连接,但您并没有要求它这样做。
  5. 您的行结尾不符合 HTTP 规范。

您可以通过尝试实现 HTTP 1.0 来使事情变得容易得多。

关于c++ - 对维基百科的 HTTP 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36267819/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com