C套接字写入HTTP GET请求:错误400

时间:2014-10-15 14:46:26

标签: c sockets httprequest

我正在编写一个小程序,使用C中的套接字从download.finance.yahoo.com读取财务数据。套接字连接似乎工作正常。

我似乎无法获得正确的GET命令来从yahoo读取数据。该程序从google.com上读得很好,我可以在那里阅读有关页面的信息。

请求:

char resource[STR_SIZE];
strcpy(resource, "GET ");
strcat(resource, argv[3]);  //argv[3]=="/d/quotes.csv?s=GOOG&f=nsl1op"
strcat(resource, "\r\n");
...
write(fd, resource, strlen(resource));

此信息位于我尝试向雅虎请求时收到的页面正文中:

status code : 400
Host Header Required
host machine: r04.ycpi.ams.yahoo.net
timestamp: 1413383465.000
url: http:///d/quotes.csv?s=GOOG

如何将GET字符串格式化以与Yahoo一起使用?

2 个答案:

答案 0 :(得分:2)

服务器要求您发送HTTP 1.1所需的实际Host标头,或者访问与根域共享相同IP的子域上的资源,例如:

char request[STR_SIZE];
strcpy(request, "GET ");
strcat(request, argv[3]); // "/d/quotes.csv?s=GOOG&f=nsl1op"
strcat(request, " HTTP/1.1\r\n");
strcat(request, "Host: ");
strcat(request, argv[4]); // "download.finance.yahoo.com"
strcat(request, "\r\n");
// other HTTP headers as needed
strcat(request, "\r\n");
...
write(fd, resource, strlen(resource));

可替换地:

char request[STR_SIZE];
sprintf(request,
    "GET %s HTTP/1.1\r\n"
    "Host: %s\r\n"
    // other headers as needed
    "\r\n",
    argv[3], // "/d/quotes.csv?s=GOOG&f=nsl1op"
    argv[4]  // "download.finance.yahoo.com"
    //...
);
...
write(fd, request, strlen(request));

答案 1 :(得分:-1)

当您阅读错误消息和回复中的数据时,您可以看到问题所在:

错误消息是"主机标头必需"并且网址为" http:///d/quotes.csv?s=GOOG",因此应在GET请求中添加主机名,例如

char resource[STR_SIZE];
strcpy(resource, "GET ");

strcat(resource, "download.finance.yahoo.com"); // or add it from argument or variable

strcat(resource, argv[3]);  //argv[3]=="/d/quotes.csv?s=GOOG&f=nsl1op"
strcat(resource, "\r\n");
...
write(fd, resource, strlen(resource));