1 # This file is part of NIT ( http://www.nitlanguage.org ).
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at
7 # http://www.apache.org/licenses/LICENSE-2.0
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 # See the License for the specific language governing permissions and
13 # limitations under the License.
15 # Shortcut services for scripts: `http_get` and `http_download`
22 # Execute a simple HTTP GET request to the URL `self`
24 # Set `accept_status_code` to the expected response HTTP code, defaults to 200.
25 # If a different status code is received, the return code is printed to stderr.
27 # Returns the response body on success and `null` on error. Prints the error
30 # For more control, set HTTP request headers, keep the response status code
31 # and much more, use `CurlHTTPRequest`.
34 # assert "http://example.com/".http_get != null
36 fun http_get
(accept_status_code
: nullable Int): nullable String
38 var req
= new CurlHTTPRequest(self.to_s
)
39 var resp
= req
.execute
42 if resp
isa CurlResponseSuccess then
43 if resp
.status_code
== (accept_status_code
or else 200) then
46 print_error
"HTTP request failed: server returned {resp.status_code}"
48 else if resp
isa CurlResponseFailed then
49 print_error
"HTTP request failed: {resp.error_msg}"
54 # Download the file at URL `self` to `output_path` with a simple HTTP request
56 # If not set, `output_path` defaults to `self.basename`.
58 # Set `accept_status_code` to the expected response HTTP code, defaults to 200.
59 # If a different status code is received, the return code is printed to stderr.
61 # Returns the path to the downloaded file on success and `null` on errors.
62 # Prints the error message to stderr.
64 # For more control, set HTTP request headers, keep the response status code
65 # and much more, use `CurlHTTPRequest`.
68 # assert "http://example.com/".http_download("index.html") == "example.com"
70 fun http_download
(output_path
: nullable Text, accept_status_code
: nullable Int): nullable String
72 var path
= (output_path
or else self.basename
).to_s
74 var req
= new CurlHTTPRequest(self.to_s
)
75 var resp
= req
.download_to_file
(path
)
78 if resp
isa CurlFileResponseSuccess then
79 if resp
.status_code
== (accept_status_code
or else 200) then
82 print_error
"HTTP request failed: server returned {resp.status_code}"
84 else if resp
isa CurlResponseFailed then
85 print_error
"HTTP request failed: {resp.error_msg}"