使用套接字发出Http请求

时间:2013-04-29 10:45:13

标签: ios sockets

我试图发出GET / POST请求。 GET请求现在。我能够建立连接,但我得到的响应永远不会200 OK。这是代码

   int socketFD;
    struct sockaddr_in myaddr;
    //    struct sockaddr_in hints;
    socketFD = socket(AF_INET, SOCK_STREAM, 0);
    if (socketFD == -1) {
        NSLog(@"Error in making socket");
    }      
    myaddr.sin_port = htons(80);
    memset(&myaddr.sin_zero, '\0', 8);


    char *sendbug = "GET 173.194.66.99 HTTP/1.0\r\n\r\n";


    struct sockaddr_in dest,their_addr;
    //    struct addrinfo *res;
    struct sockaddr sockAddrToDisplay;

    dest.sin_family = AF_INET;
    dest.sin_port = htons(80);
    NSLog(@"%s",sendbug);
    dest.sin_addr.s_addr = inet_addr("173.194.66.99"); // IP for google


    int connectResult =    connect(socketFD, (struct sockaddr *)&dest, sizeof(struct sockaddr));

    if (connectResult == -1) {
        NSLog(@"Error connecting");
    }

    int sendResult =   sendto(socketFD, sendbug, strlen(sendbug), 0, (struct sockaddr *)&dest, sizeof(struct sockaddr));

    if (sendResult == -1) {
        NSLog(@"Sendind failed");
    }

    //    int peerResult =    getpeername(socketFD, (struct sockaddr *)&dest,(socklen_t *) sizeof(struct sockaddr));


    struct addrinfo hints, *res;
    int sockfd;
    int byte_count;
    socklen_t fromlen;
    struct sockaddr_storage addr;
    char buf[512];
    char ipstr[INET6_ADDRSTRLEN];


    fromlen = sizeof addr;
    byte_count = recvfrom(socketFD, buf, sizeof buf, 0,(struct sockaddr *) &addr, &fromlen);

    NSLog(@"%s",buf);

回应。我在做错的地方需要一些帮助,以及我如何制作一个http POST请求。先发制人员

<html>
<head><title>400 Bad Request</title></head>
<body bgcolor="white">
<center><h1>400 Bad Request</h1></center>
<hr><center>nginx/1.3.7</center>
</body>
</html>
∑¥ëXnr

1 个答案:

答案 0 :(得分:4)

你的问题在这里:

char *sendbug = "GET 173.194.66.99 HTTP/1.0\r\n\r\n";

HTTP协议将请求定义为<method> <resource> [HTTP/<version>]。版本默认为1.0,在1.0中你最后只需要一个换行符,而你要求的资源是主页,所以这应该是:

char *sendbug = "GET /\r\n";

如果您尝试实现自定义客户端,我建议您阅读HTTP-RFC,这也应该可以帮助您构建POST请求。并且请升级到HTTP / 1.1,而不是所有的网络服务器都不再需要支持1.0。

RFC 2616 - Hypertext Transfer Protocol -- HTTP/1.1