英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论