如何在D语言中使用JSON数据进行HTTP POST请求

huangapple go评论59阅读模式
英文:

How to make an http POST request with JSON data in D

问题

(1) 定义 JSON 载荷

(2) 使用多行字符串

(3) 指定 HTTP 标头字段,如 "Content-Type"

(4) 发送带有 JSON 数据的 POST 请求

(5) 接收来自服务器的响应并在屏幕上打印出来

(6) 在 D 编程语言中

(7) 如何编译和运行

英文:

How to

(1) define the JSON payload

(2) using a multiline string

(3) specify the http header fields such as "Content-Type"

(4) send the POST request with the JSON data

(5) receive the response from the server and print it on screen

(6) in the D programming language

(7) how to compile and run

答案1

得分: 2

以下是D语言中的通用JSON POST请求,原始多行JSON包含在单引号'中,代码将保存在名为test.d的文本文件中:

import std.stdio;
//import std.json;
import std.net.curl;

void main()
{
    string payload = '{
        "a": "b",
        "c": false,
        "e": [[1, 2], [3.3, 4.4]],
        "f": ["g", "h"],
        "i": 0.5
    }';
    auto http = HTTP();
    http.addRequestHeader("Content-Type", "application/json");
    http.addRequestHeader("Authorization", "");
    auto content = post("https://your/rest/api", payload, http);
    writeln(content);
    /*JSONValue j = parseJSON(payload); //extra debug, uncomment the import too
    writeln(j);
    writeln(j.type);
    writeln(j["a"].str);
    writeln(j["e"].array);
    writeln(j["c"].type);
    writeln(j["i"].floating);
    writeln(payload);*/
}

在Linux上编译如下:

gdc test.d

运行如下:

./a.out
英文:

here is a generic JSON POST request in D; the raw multiline JSON is enclosed in single quotes ', code to be saved in a text file such as test.d:

import std.stdio;
//import std.json;
import std.net.curl;
void main()
{
	string payload = '{
       "a": "b",
       "c": false,
       "e": [[1,2],[3.3,4.4]],
       "f": ["g","h"],
       "i": 0.5
    }';
    auto http = HTTP();
	http.addRequestHeader("Content-Type", "application/json");
	http.addRequestHeader("Authorization", "");
	auto content = post("https://your/rest/api", payload, http);
	writeln(content);
	/*JSONValue j = parseJSON(payload); //extra debug, uncomment the import too
	writeln(j);
	writeln(j.type);
	writeln(j["a"].str);
	writeln(j["e"].array);
    writeln(j["c"].type);
	writeln(j["i"].floating);
    writeln(payload);*/
}

on linux, compile like this:

gdc test.d

run like this:

./a.out

huangapple
  • 本文由 发表于 2023年7月10日 19:33:46
  • 转载请务必保留本文链接:https://go.coder-hub.com/76653317.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定