-
Notifications
You must be signed in to change notification settings - Fork 31
Home
###Make a simple Request###
Making request with dlang-requests is very simple. First of all install and import requests module:
import requests;
Now, if everything we need, is content of some webpage we can just receive it:
auto content = getContent("http://httpbin.org/");
getContent fetch complete document to buffer and return it to the caller. content can be converted to string, or can be used as range. For example, if you need to count lines in content, you can directly apply splitter and count:
writeln(content.splitter('\n').count);
or count non-empty lines:
writeln(content.splitter('\n').filter!"a!=``".count);
Actually buffer is ForwardRange with length and random access, so you can apply many algorithms directly to it. Or you can extract data in form of ubyte[], using method data:
ubyte[] data = content.data;
###Request with Parameters ###
If you need to pass some parameters to query, requests propose simple way to do it. For example you have a search query with some parameters: name - person name, age - personage, and so on... You can pass all parameters to get using queryParameters() helper:
auto content = getContent("http://httpbin.org/get", queryParams("name", "any name", "age", 42));
When you print response content with writeln(content); You will see that server recognized your parameters:
{
"args": {
"age": "42",
"name": "any name"
},
"headers": {
"Accept-Encoding": "gzip, deflate",
"Host": "httpbin.org",
"User-Agent": "dlang-requests"
},
"origin": "xxx.xxx.xxx.xxx",
"url": "http://httpbin.org/get?name=any name&age=42"
}
Or, you can pass dictionary:
auto content = getContent("http://httpbin.org/get", ["name": "any name", "age": "42"]);
This request will give you the same response.
Here is link to submodules docs: