-1

我有以下字符串:

HTTP/1.1 200 OK
Date: Tue, 06 Dec 2011 11:53:22 GMT
Server: Apache/2.2.14 (Ubuntu)
X-Powered-By: PHP/5.3.2-1ubuntu4.9
Vary: Accept-Encoding
Content-Encoding: gzip
Content-Length: 48
Content-Type: text/html

��(�ͱ���I�O����H�����ч��
                          �4�@��AQ������t

我想提取到"\r\n\r\n",丢弃二进制数据。IE :

HTTP/1.1 200 OK
Date: Tue, 06 Dec 2011 11:53:22 GMT
Server: Apache/2.2.14 (Ubuntu)
X-Powered-By: PHP/5.3.2-1ubuntu4.9
Vary: Accept-Encoding
Content-Encoding: gzip
Content-Length: 48
Content-Type: text/html

如何在 C 中做到这一点?

4

2 回答 2

6

这可以通过简单地找到前两个连续换行符来轻松完成,因为这会终止标头,然后将所有内容复制到该点到一个单独的缓冲区:

// Find the end of the header, which is terminated
// by two line breaks
char* end = strstr(header, "\r\n\r\n");
char* buffer = 0;
if (end) {
    // Allocate memory to hold the entire header
    buffer = malloc((end - header) + 1);
    if (buffer) {
        // Copy header to buffer
        memcpy(buffer, header, end - header);
        // NULL terminate the buffer
        buffer[end - header] = 0;
        // Do something with the buffer here
    
        // Don't forget to release the allocated memory
        free(buffer);
    }
}
于 2011-12-06T12:46:32.223 回答
1

您可以使用strstr函数。

但请注意,对于 HTTP 客户端(如libcurl)和 HTTP 服务器(如onion )端存在良好的 C 库。HTTP的细节很复杂。

于 2011-12-06T12:46:10.787 回答