Skip to content

HTTP Client

龙卷锋 edited this page Apr 22, 2020 · 6 revisions

HTTP Client

1. Get

import std.stdio;
import std.json;
import hunt.http.client;

void main()
{
    Request request = new RequestBuilder()
        .url("https://api.test.com/login?a=1&b=2")
        .build();
    HttpClient client = new HttpClient();
    Response response = client.newCall(request).execute();
    printf("status code: %d", response.getStatus());

    HttpBody res = response.getBody();
    writeln(res.asString());

2. Post

import std.stdio;
import std.json;
import hunt.http.client;

void main()
{
    UrlEncoded encoder = new UrlEncoded;
    encoder.put("username", "test");
    encoder.put("password", "123456");
    string content = encoder.encode();
    string contentType = "application/x-www-form-urlencoded";
    HttpBody b = HttpBody.create(contentType, content);
    Request request = new RequestBuilder()
        .url("https://api.test.com/login")
        .post(b)
        .build();
    HttpClient client = new HttpClient();
    Response response = client.newCall(request).execute();
    printf("status code: %d", response.getStatus());

    HttpBody res = response.getBody();
    writeln(res.asString());
}

Response

// Http status code
printf("status code: %d", response.getStatus());

// All header
foreach(header; response.headers())
{
    writeln("Response Header "~header.getName()~" : "~header.getValue()~"");
    writeln("\r\n");
}
// First header
string[] headers = response.headers("content-type");

// All cookie
foreach(cookie; response.cookies())
{
    writeln("name:"~cookie.getName());
    writeln("value:"~cookie.getValue());
    writeln("cookieString:"~cookie.toString());
    writeln("\r\n");
}
Clone this wiki locally