0

我试图在包含授权标头的c编程上实现http(GET请求),但问题是我无法获得(200 ok),我只有一个通信会话(服务器回复需要401授权) 但仅此而已。

**while(1){

    strcpy(buffer,"GET /mywebsite/login.html/ HTTP1.1 \n\n");
    strcat(buffer,"Host: localhost\n\n");
    strcat(buffer,"Connection: keep-alive\n\n");
    strcat(buffer,"User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.97 Safari/537.11\n\n");
    strcat(buffer,"Accept: text/html,application/xhtml+xml,application/xml;q=0.9;q=0.8\n\n");
    strcat(buffer,"Accept-Encoding: gzip,deflate,sdch\n\n");
    strcat(buffer,"Accept-Language: en-US,en;q=0.8\n\n");
    strcat(buffer,"Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.3\n\n");
    status = send(sock, buffer, strlen(buffer), 0);
    if(status == -1) {
        printf("Error in send(). Error code: %d\n", WSAGetLastError());
        continue;
    }
    buffer[0]='\0';
    //The receiving functions
    status = recv(sock, buffer, BUFFER_SIZE, 0);
    if (status == -1) {
        printf("Error in recv(). Error code: %d\n", WSAGetLastError());
        continue;
    }
    buffer[status] = '\0';
    printf("The message received is: ");
    printf("%s\n\n", buffer);

    strcpy(buffer,"GET /mywebsite/login.html/ HTTP1.1\n\n");
    strcat(buffer,"Host: localhost\n\n");
    strcat(buffer,"Authorization: Basic QWRtaW46MTIzNA== \n\n");
    strcat(buffer,"User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.97 Safari/537.11\n\n");
    strcat(buffer,"Accept: text/html,application/xhtml+xml,application/xml;q=0.9;q=0.8\n\n");
    strcat(buffer,"Accept-Encoding: gzip,deflate,sdch\n\n");
    strcat(buffer,"Accept-Language: en-US,en;q=0.8\n\n");
    strcat(buffer,"Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.3\n\n");
    strcat(buffer,"Connection: keep-alive\n\n");
    status = send(sock, buffer, strlen(buffer), 0);
    if(status == -1) {
        printf("Error in send(). Error code: %d\n", WSAGetLastError());
        continue;
    }
    buffer[0]='\0';
    //The receiving functions
    status = recv(sock, buffer, BUFFER_SIZE, 0);
    if (status == -1) {
        printf("Error in recv(). Error code: %d\n", WSAGetLastError());
        continue;
    }
    buffer[status] = '\0';
    printf("%s\n\n", buffer);
    buffer[0]='\0';

}**

第一个标头已成功发送,但下一个标头服务器无所事事(没有回复)请在这里提供一点帮助我不知道问题是什么... :(

4

1 回答 1

2

There are some obvious problems:

  • Headers should be separated by "\r\n", not "\n\n", finally ending with "\r\n\r\n".
  • send and recv should be retried on errno==EINTR
  • send may send less bytes than requested, so it should be used in a loop to ensure all data are transferred.
于 2013-01-04T17:02:24.917 回答