我需要解析 header 以从 http 请求中提取绝对 URL。 我只关心的Method只有GET、POST和HEAD。我想确认以下简单的逻辑/伪代码足以涵盖大多数情况,
1 url = extract the url from the first request line;
2 if (url[0] == '/') {
3 //relative url, keep reading until HOST or end of the header
4 while (nextline != "\r\n\r\n") {
5 if (nextline starts with HOST) {
6 host = extract the host value;
7 return (host+url);
8 } else {
9 continue;
10 }
11
12 }
13 return bad_req;
14 } else {
15 //absolute url, return directly, ignore HOST
16 return url;
17 }
1)还有遗漏的情况吗?
2) 第 2 行是否足以判断它是相对 URL 还是绝对 URL?
3)编码重要吗?
4)其他可能的故障?
顺便说一句,性能是我需要考虑的一个非常重要的因素。
最佳答案
nextline != "\r\n\r\n"<---- 这在 C 中不起作用
尝试 while ( strcmp (nextline, "\r\n\r\n") == 0 )
if (nextline starts with HOST)
if ( strncmp(nextline, "http://www.frogs.com", strlen(nextline)) == 0)
== 0 表示匹配。如果不匹配,结果小于或大于 0。上面的行取决于下一行的字符串长度 >=“http://www.frogs.com”的字符串长度。
“顺便说一句,性能是我需要考虑的一个非常重要的因素。”
C 具有裸机性能 =“光速”。既要编写低性能的 C 代码,又要有足够高的能力水平来编写编译时不会出现警告且不会崩溃的 C 代码,需要大量的技能。
关于C:HTTP头解析,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14493090/