我有在微控制器上运行的http服务器。它提供一个包含表单的简短html网页。填写表单并单击使用POST方法提交后,我将收到如下表单值:

Key1=value1&Key2=value2&Key3=value3&...

接收到的全部数据以字符串形式保存在缓冲区中。

问题是:如何通过将每个key = vale保存在变量中来处理这些数据。例如:

int key1 = value1int key2 = value2int key3 = value3

非常感谢你

最佳答案

这是我的主要评论的开头。

这是带有测试用例的完整实现:

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

enum {
    KEY1,
    KEY2,
    KEY3
};

typedef struct keyPlusValue {
    char *key;
    int value;
} keyPlusValue_t;

keyPlusValue_t symlist[] = {
    [KEY1] = { "key1", 0 },
    [KEY2] = { "key2", 0 },
    [KEY3] = { "key3", 0 },
};

int symcount = sizeof(symlist) / sizeof(symlist[0]);

void
parse_list(const char *str)
{
    char buf[strlen(str) + 1];
    char *bp;
    char *tok;
    char *val;
    keyPlusValue_t *symtry;
    keyPlusValue_t *symok;

    // NOTE: we _must_ create a copy of the string because caller could pass
    // in a constant string and we are going to _write_ into our copy
    strcpy(buf,str);

    bp = buf;
    while (1) {
        // get next "key=val" pair
        tok = strtok(bp,"&");
        if (tok == NULL)
            break;
        bp = NULL;

        // split up pair into "key" and "value"
        val = strchr(tok,'=');
        if (val == NULL) {
            printf("malformed token -- '%s'\n",tok);
            break;
        }
        *val++ = 0;

        // scan symbol/key table looking for match
        symok = NULL;
        for (symtry = symlist;  symtry < &symlist[symcount];  ++symtry) {
            if (strcmp(tok,symtry->key) == 0) {
                symok = symtry;
                break;
            }
        }

        // if no match found -- should not happen but _must_ be checked for
        if (symok == NULL) {
            printf("unknown key -- '%s'\n",tok);
            break;
        }

        // convert text representation of number into int
        symok->value = atoi(val);
    }
}

void
test(const char *str)
{
    keyPlusValue_t *sym;

    printf("\n");
    printf("test: '%s'\n",str);

    parse_list(str);

    for (sym = symlist;  sym < &symlist[symcount];  ++sym)
        printf(" key='%s' val=%d\n",sym->key,sym->value);
}

int
main(void)
{

    test("key1=1&key2=2&key3=3");
    test("key1=2&key2=3&key3=4");
    test("key1=3&key2=4&key3=5");

    return 0;
}

关于c - 如何使用C语言处理http服务器接收的<form>数据,例如(key = value&key = value&key = value&…),并将每个值分配给变量?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/54189855/

10-12 16:02