我试图使用C获取此页面的HTML http://pastebin.com/raw/7y7MWssc。到目前为止,我试图使用套接字&端口80连接到pastebin,然后使用HTTP请求获取HTML在该pastebin页面上。C语言,获取HTML源码
我知道我到目前为止大概是遥远,但在这里它是:上述
#include <stdio.h>
#include <string.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
int main()
{
/*Define socket variables */
char host[1024] = "pastebin.com";
char url[1024] = "/raw/7y7MWssc";
char request[2000];
struct hostent *server;
struct sockaddr_in serverAddr;
int portno = 80;
printf("Trying to get source of pastebin.com/raw/7y7MWssc ...\n");
/* Create socket */
int tcpSocket = socket(AF_INET, SOCK_STREAM, 0);
if(tcpSocket < 0) {
printf("ERROR opening socket\n");
} else {
printf("Socket opened successfully.\n");
}
server = gethostbyname(host);
serverAddr.sin_port = htons(portno);
if(connect(tcpSocket, (struct sockaddr *) &serverAddr, sizeof(serverAddr)) < 0) {
printf("Can't connect\n");
} else {
printf("Connected successfully\n");
}
bzero(request, 2000);
sprintf(request, "Get %s HTTP/1.1\r\n Host: %s\r\n \r\n \r\n", url, host);
printf("\n%s", request);
if(send(tcpSocket, request, strlen(request), 0) < 0) {
printf("Error with send()");
} else {
printf("Successfully sent html fetch request");
}
printf("test\n");
}
的代码是有意义的某一点,现在我很困惑。我如何使这个从http://pastebin.com/raw/7y7MWssc获得网络资源?
1)去除多余的空格在请求行的开始,2)改变获取到GET ,3)收到回应并打印出来 – immibis
@immibis完成了,但是在第38行打印请求后,仍然存在问题,因为最后一行打印“测试”从未执行过。 – BotHam
它是“从未执行过的”?那么,你的程序是......退出时出现错误?挂?如果它挂着,它会卡在哪一行?如果有错误,它是什么? – larsks