0

I'm a very beginner on using sockets with C standard library in Objective-C. I'm trying to make HTTP requests to fetch pages on a self-developed browser, to this we're using a query request such as follows:

+(NSData*)fetchWebPageForURL:(NSURL*)url error:(NSError **)anError {
    //[...]
    const char* query = [[NSString stringWithFormat:@"GET /%s HTTP/1.1\r\nHost: %s\r\nUser-Agent: %@\r\nConnection: close\r\n\r\n",
                                page, hostname, userAgentAsNSString] cStringUsingEncoding:NSUTF8StringEncoding];
    //[...]
}

Where page is the path (if exists), hostname is the URL, and user agent is some device information such as iOS version, device name and so on. The socket has been created with the following protocols and types:

+(NSData*)fetchWebPageForURL:(NSURL*)url error:(NSError **)anError {
    //socket creation with TCP protocol and IPv4.
    int sockfd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);

    //[...]

    //send request query to the server
    size_t sentSoFar = 0;
    do {
        size_t bytesSent = write(sockfd, query + sentSoFar, strlen(query) - sentSoFar);
        if(bytesSent == -1)
        {
            //send error message

            close(sockfd);
            return nil;
        }
        else if (bytesSent == 0)
        {
            // All done.
            break;
        }

        sentSoFar += bytesSent;

    } while (sentSoFar < strlen(query));

    //[...]

    // Read the response from the server.
    int BUFFER_SIZE = 1024;
    char response[BUFFER_SIZE];

    fd_set rfds;
    struct timeval tv;
    bool htmlStarted = false;
    int done = 0;;

    size_t bytesRead = read(sockfd, response, BUFFER_SIZE);

    //parsing response
}

The problem is that no matter what kind of URL we sent (with http or https scheme) if the page does not support HTTP/1.1 the response status is always HTTP/1.1 301 Moved Permanently. Our solution shows the response body (using stackoverflow's url as example: stackoverflow.com):

<HTML><HEAD><meta http-equiv="content-type" content="text/html;charset=utf-8">
<TITLE>301 Moved</TITLE></HEAD><BODY>
<H1>301 Moved</H1>
The document has moved
<A HREF="https://www.stackoverflow.com/">here</A>.
</BODY></HTML>

When we click on the link and send the new URL with HTTPS scheme, the response with status 301 still happens. We already tried to change our query to HTTP/2 but the same response (with HTTP/1.1) is still received. I think that can be a problem with my sockets configuration, but here enters the part that I'm not familiar with, so I don't know what to do.

4

0 回答 0