C语言 如何在 C 中解析 HTTP 响应?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2395207/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 04:45:01  来源:igfitidea点击:

How to parse HTTP responses in C?

chttpparsing

提问by Güter M.

I'm writing a little project which interacts with a set of servers using HTTP 1.1 GET and POST. The server gives me the response after some header lines, so I though on using strtok()function using \nas the delimiter but there is a crash whenever I try to do so.

我正在编写一个小项目,它使用 HTTP 1.1 GET 和 POST 与一组服务器进行交互。服务器在一些标题行之后给了我响应,所以我虽然使用strtok()函数\n作为分隔符,但是每当我尝试这样做时都会发生崩溃。

Is there any simple way to parse a HTTP response in C? I would like not to use 3rd party libraries for this but if it was really necesary I won't have any problem.

有什么简单的方法可以在 C 中解析 HTTP 响应?我不想为此使用 3rd 方库,但如果真的有必要,我不会有任何问题。

Thank you very much for everything.

非常感谢你所做的一切。

EDIT: Here is some example code, just trying to print the lines:

编辑:这是一些示例代码,只是尝试打印行:

char *response = "HTTP/1.1 200 OK\nServer: Apache-Coyote/1.1\nPragma: no-cache"

char *token = NULL;
token = strtok(response, "\n");
while (token) {
    printf("Current token: %s.\n", token);
    token = strtok(NULL, "\n");
}

回答by Eli Bendersky

http-parseris a simple and super-fast HTTP parser written in C for the Node.js project

http-parser是一个用 C 语言为 Node.js 项目编写的简单且超快的 HTTP 解析器

It's only 2 C files, without any external dependencies.

它只有 2 个 C 文件,没有任何外部依赖。

回答by Jerry Coffin

The problem in the code you've posted is pretty simple: strtokworks by modifying the string you pass to it. Modifying a string literal gives undefined behavior. A truly minuscule change to your code lets it work (I've also headed the appropriate headers, and moved the executable part into a function:

您发布的代码中的问题非常简单:strtok通过修改传递给它的字符串来工作。修改字符串文字会产生未定义的行为。对您的代码进行真正微小的更改即可使其工作(我还引导了适当的标头,并将可执行部分移到了一个函数中:

#include <string.h>
#include <stdio.h>

char response[] = "HTTP/1.1 200 OK\nServer: Apache-Coyote/1.1\nPragma: no-cache";

int main() { 
    char *token = NULL;
    token = strtok(response, "\n");
    while (token) {
        printf("Current token: %s.\n", token);
        token = strtok(NULL, "\n");
    }
    return 0;
}

In real use, you'll be reading the HTTP response into a buffer anyway; the problem you encountered only arises in a trivial test case like you generated. At the same time, it does point to the fact that strtokis a pretty poorly designed function, and you'd almost certainly be better off with something else.

在实际使用中,您无论如何都会将 HTTP 响应读入缓冲区;您遇到的问题只出现在像您生成的琐碎测试用例中。同时,它确实指出了strtok一个设计非常糟糕的功能的事实,而且几乎可以肯定你会更好地使用其他东西。