练习使用 socket 发送简单的 HTTP GET 请求(二)
rn += 4;
content = rnrn;
if (-1 == n_content_len)
{
const char *content_length = strstr(p_receive, "Content-Length: ");
if (NULL != content_length && content_length < p_buf)
{
content_length += 16;
const char *rn = strstr(content_length, "\r\n");
if (NULL != rn && rn < p_buf)
{
int count = rn - content_length;
strncpy(temp, content_length, count);
temp[count] = '\0';
n_content_len = atoi(temp);
}
}
if (-1 == n_content_len)
{
const char *rn = strstr(rnrn, "\r\n");
if (NULL != rn && rn < p_buf)
{
int count = rn - rnrn;
strncpy(temp, rnrn, count);
temp[count] = '\0';
if (1 == sscanf(temp, "%x", &n_content_len) )
{
n_content_len += 7; // 0D 0A 30 0D 0A 0D 0A
content = rn + 2;
}
}
}
if (-1 == n_content_len)
{
const char *connection = strstr(p_receive, "Connection: ");
if (NULL != connection && connection < p_buf)
{
connection += 12;
const char *rn = strstr(connection, "\r\n");
if (NULL != rn && rn < p_buf)
{
int count = rn - connection;
strncpy(temp, connection, count);
temp[count] = '\0';
connection = _strupr(temp);
if (0 == strcmp(connection, "CLOSE"))
n_content_len = 0;
}
}
}
}
}
if (NULL != content && n_content_len > 0)
{
n_head_len = content - p_receive;
int n_cur_len = p_buf - p_receive;
if ( n_cur_len >= n_head_len + n_content_len )
break;
}
}
}
n_len = n_buf_len - 1 - n_len;
n_buf_len = n_len;
p_receive[n_len] = '\0';
}
err = ::closesocket(sock);
if ( SOCKET_ERROR == err )
{
printf("[connectAndSendData]: closesocket error %d. \r\n", WSAGetLastError());
}
::WSACleanup();
return 0;
}
int main()
{
char request_buffer[1024];
request_buffer[0] = '\0';
// 写 HTTP 头信息
// HTPP 头可以有多行,每行都以 \r\n 结尾,最后再以 \r\n 结束
strcat(request_buffer, "GET /index.php id=1 HTTP/1.1\r\n");
strcat(request_buffer, "Host: 127.0.0.1:80\r\n");
strcat(request_buffer, "Connection: keep-alive\r\n");
strcat(request_buffer, "Accept: */*\r\n");
strcat(request_buffer, "\r\n");
char receive_buff[102400];
unsigned n_receive_len = 102400;
receive_buff[0] = '\0';
connectAndSendData("127.0.0.1", 80, request_buffer, strlen(request_buffer), receive_buff, &n_receive_len);
printf(rece