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

98 views Asked by At

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

There are 1 answers

0
jmarina On BEST ANSWER

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