0

テストがあり、JSON データをサーバーに送信する必要があります。次のテストがあります。

extern crate hyper;
extern crate rustc_serialize;

use std::io::Read;
use hyper::*;

#[derive(RustcDecodable, RustcEncodable)]
struct LegacyJsonRequest {
    jsonrpc: String,
    method: String,
    params: String,
    id: i32,
    auth: String,
}

#[test]
fn apiinfo_jsonrpc_tests() {
    let client = Client::new();

    let url = "http://localhost:6767/api_jsonrpc.php";

    let mut http_reader = header::Headers::new();
    http_reader.set_raw("Content-Type", vec![b"application/json".to_vec()]);

    //TODO: How to use a struct and 'export' it to a raw string literal???
    let request_data = LegacyJsonRequest {
        jsonrpc: "2.0".to_string(),
        method: "apiinfo.version".to_string(),
        params: "[]".to_string(),
        auth: "[]".to_string(),
        id: 1,
    };

    let encoded_request = rustc_serialize::json::encode(&request_data).unwrap();

    let mut response = client.post(url)
        .body(encoded_request)
        .send()
        .unwrap();

}

このコードでは、次のエラーが返されます。

error[E0277]: the trait bound `hyper::client::Body<'_>: std::convert::From<std::string::String>` is not satisfied

構造体と JSON でエンコードされたコードを削除し、単純な生の文字列リテラルを作成して body メソッドで参照すると、機能します。例:

extern crate hyper;
extern crate rustc_serialize;

use std::io::Read;
use hyper::*;

#[derive(RustcDecodable, RustcEncodable)]
struct LegacyJsonRequest {
    jsonrpc: String,
    method: String,
    params: String,
    id: i32,
    auth: String,
}

#[test]
fn apiinfo_jsonrpc_tests() {
    let client = Client::new();

    let url = "http://localhost:6767/api_jsonrpc.php";

    let mut http_reader = header::Headers::new();
    http_reader.set_raw("Content-Type", vec![b"application/json".to_vec()]);

    let request_data =
        r#"{"jsonrpc":"2.0", "method": "apiinfo.version", "params": {}, "auth": {}, "id": "1"}"#;

    let mut response = client.post(url)
        .body(request_data)
        .send()
        .unwrap();

}

では、構造体または JSON をraw stringに変換するにはどうすればよいですか?

エラー E0277 が「Hyper::client::Body<'_>」の特性の実装に関するものであることは知っていますが、これは問題ではありません。問題は、構造体または JSON を生の文字列に変換する方法だけです。ありがとう。

4

1 に答える 1