我正在写一个简单的函数,从HTTP响应中分离binary/post-data/html。 HTTP头由\r\n\r\n
终止,剩下的就是消息。如何从http响应中分离binary/post-data/html?
我已经写了这个:
#define MAX_BUFFER_SIZE 256
//...
int size = 0;
int buf_size = MAX_BUFFER_SIZE;
char * headers = malloc(MAX_BUFFER_SIZE);
char * newbuf;
while(httpresponse[size]) {
if(httpresponse[size] == '\r' &&
httpresponse[size + 1] == '\n' &&
httpresponse[size + 2] == '\r' &&
httpresponse[size + 3] == '\n') {
break;
}
headers[size] = httpresponse[size];
if(size >= buf_size) {
buf_size += MAX_BUFFER_SIZE;
newbuf = realloc(headers, buf_size);
if(NULL == newbuf) exit(1);
headers = newbuf;
}
size ++;
}
printf("%s\n", headers);
的httpresponse
变量,具有价值,如:
HTTP/1.1 200 OK
Date: Fri, 23 Mar 2012 15:28:17 GMT
Expires: Sat, 23 Mar 2013 15:28:17 GMT
Cache-Control: public, max-age=31536000
Last-Modified: Thu, 14 Apr 2011 15:46:35 GMT
Content-Type: image/jpeg
Content-Length: 12745
X-XSS-Protection: 1; mode=block
Connection: close
���������I1��} �g������'�B�f�p���ohd]sft�����J�������1����瘿ٱ����$3�G�8��4=�E�i����ܼG����H��nbi�"�1��b[Ǘl��++���OPt�W��>�����i�]t�QT�N/,Q�Qz������0�` N7���M��f��S�Š�x9k��$*
//more binary...
但上面的C程序,打印以下文字:
HTTP/1.1 200 OK
Date: Fri, 23 Mar 2012 17:12:09 GMT
Expires: Sat, 23 Mar 2013 17:12:09 GMT
Last-Modified: Thu, 14 Apr 2011 15:46:35 GMT
Content-Type: image/jpeg
Content-Length: 12745
X-XSS-Protection: 1; mode=block
Cache-Control: public, max-age=31536000
Age: 3746
�2�/���ms���|ނ����LQr2K3�v��J.�,�z��^Oy����s(ct���X`iA����I����U�{
代替:
HTTP/1.1 200 OK
Date: Fri, 23 Mar 2012 15:28:17 GMT
Expires: Sat, 23 Mar 2013 15:28:17 GMT
Cache-Control: public, max-age=31536000
Last-Modified: Thu, 14 Apr 2011 15:46:35 GMT
Content-Type: image/jpeg
Content-Length: 12745
X-XSS-Protection: 1; mode=block
Connection: close
如何解决这个问题?提前致谢。
呀,真的。我在'printf()'之前添加了0-终止符,但是我得到相同的错误.. – Jack 2012-03-23 19:11:16
嗯 - 而httpresponse是一个“单字节宽”字符串 - 如何使用“strstr”函数来寻找而不是使用while循环? –
2012-03-23 19:24:34
我试过了。但是如果我用strstr()分割'\ r \ n \ r \ n',它只会返回二进制。我想分割标题和正文(消息),因为这个原因,我用while循环。 – Jack 2012-03-23 19:37:39