【问题标题】:actix-web json unexpected behavioractix-web json 意外行为
【发布时间】:2021-11-24 07:05:13
【问题描述】:

我在玩actix-web 时遇到了以下问题。 我有 2 个函数,一个函数接受后字符串请求并返回结构的 json,另一个接受结构的 json 并返回字符串。但是,采用 json 结构会出现错误 400。

结构代码

#[derive(Deserialize, Serialize)]
pub struct MyObj {
    pub name: String,
}

功能

#[post("/simple")]
pub async fn simple(obj: String) -> impl Responder {
    MyObj {
        name: obj,
    }
}

#[post("/simplerecv")]
pub async fn simplerrecv(_obj: web::Json<MyObj>) -> String {
    println!("Inside simplerecv");
    "Hello".to_owned()
}

用于测试的 Python 代码

def simple():
    # testing simple
    data = "hello44444"
    r1 = requests.post("http://127.0.0.1:8080/simple", data=json.dumps(data))
    print(r1.status_code, type(r1.text), r1.text)
    res = json.loads(r1.text)
    r2 = requests.post("http://127.0.0.1:8080/simplerecv",
                       data=json.dumps(json.loads(r1.text)))
    print(r2.status_code)

Python 代码的输出

200 {"name":""hello44444""}
400

【问题讨论】:

    标签: rust actix-web


    【解决方案1】:

    一些网络服务器不接受没有Content-Type: application/json 的 JSON,actix-web 也是如此。

    r2 = requests.post("http://127.0.0.1:8080/simplerecv",
                       headers={'Content-Type': 'application/json;charset=utf-8'},
                       data=json.dumps(json.loads(r1.text)))
    

    【讨论】:

    • 包含;charset=utf-8 既没有必要(在与符合标准的系统通信时)也不正确——application/json 类型的规范没有定义 charset 参数,并指定编码为 UTF-8。 (在实践中这可能是必要的,因为特定的不符合要求的实现不解码为 UTF-8,因为它们应该,除非特别告知,但如果您不将请求发送到这样的不合格的网络服务器。)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-08-05
    • 2021-05-13
    • 2020-01-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多