mdref.json config
[mdref/mdref-http] / http / Client / : Examples.md
1 # http\Client Examples
2
3 ## Sending a simple GET request:
4
5 <?php
6
7 $request = new http\Client\Request("GET",
8 "http://localhost",
9 ["User-Agent"=>"My Client/0.1"]
10 );
11 $request->setOptions(["timeout"=>1]);
12
13 $client = new http\Client;
14 $client->enqueue($request)->send();
15
16 // pop the last retrieved response
17 $response = $client->getResponse();
18 printf("%s returned '%s' (%d)\n",
19 $response->getTransferInfo("effective_url"),
20 $response->getInfo(),
21 $response->getResponseCode()
22 );
23 ?>
24
25 ### Yields:
26
27 http://localhost/ returned 'HTTP/1.1 200 OK' (200)
28
29
30 ## Submitting a standard form:
31
32 <?php
33
34 $request = new http\Client\Request("POST",
35 "http://localhost/post.php",
36 ["Content-Type" => "application/x-www-form-urlencoded"]
37 );
38 $request->getBody()->append(new http\QueryString([
39 "user" => "mike",
40 "name" => "Michael Wallner"
41 ]));
42
43 $client = new http\Client;
44 $client->setOptions(["ssl" => [
45 "version" => http\Client\Curl\SSL_VERSION_TLSv1
46 ]]);
47 $client->enqueue($request)->send();
48
49 // ask for the response for this specific request
50 $response = $client->getResponse($request);
51 printf("-> %s\n", $response->getInfo());
52
53 ?>
54
55 ### Yields:
56
57 -> HTTP/1.1 200 OK
58
59
60 ## Submitting a multipart form:
61
62 <?php
63
64 $request = new http\Client\Request("POST",
65 "http://localhost/post.php"
66 );
67
68 // http\Message\Body::addForm() will automatically add
69 // Content-Type: multipart/form-data to the request headers
70 $request->getBody()->addForm([
71 "user" => "mike",
72 "name" => "Michael Wallner"
73 ], [
74 [
75 "name" => "image",
76 "type" => "image/jpeg",
77 "file" => "image.jpg"
78 ]
79 ]);
80
81 $client = new http\Client;
82 $client->setOptions(["ssl" => [
83 "version" => http\Client\Curl\SSL_VERSION_TLSv1
84 ]]);
85 $client->enqueue($request)->send();
86
87 // ask for the response for this specific request
88 $response = $client->getResponse($request);
89 printf("-> %.2F kB\n @ %.2F Mbit",
90 .001 * $response->getTransferInfo("size_upload"),
91 .0000008 * $response->getTransferInfo("speed_upload")
92 );
93 ?>
94
95 ### Yields:
96
97 -> 15.98 kB @ 6.77 Mbit