Rust
Rust
Read the REST Response Body into a Stream
See more REST Examples
Demonstrates Rest.ReadRespBodyStream, which reads the response body into a Stream. The optional flag sets the stream character set from the response Content-Type charset for textual responses.
The file paths are relative to the application's current working directory. Absolute paths may also be used. Supply the paths appropriate to your own environment.
Background. The staged request model separates sending from reading: a
SendReq method transmits the request, ReadResponseHeader reads the status line and headers, and a ReadResp method reads the body. This gives fine control over large or streamed messages compared with the single-call full-request methods.Chilkat Rust Downloads
let rest = chilkat::Rest::new();
let b_tls = true;
let b_auto_reconnect = true;
if rest.connect("example.com", 443, b_tls, b_auto_reconnect).is_err() {
println!("{}", rest.last_error_text());
return;
}
// The file paths are relative to the application's current working directory. Absolute paths
// may also be used. Supply the paths appropriate to your own environment.
if rest.send_req_no_body("GET", "/api/images/1").is_err() {
println!("{}", rest.last_error_text());
return;
}
let status_code = rest.read_response_header();
if status_code < 0 {
println!("{}", rest.last_error_text());
return;
}
// Check for the expected success status code. If the response is not 200, the body is likely
// error text formatted as JSON, XML, or HTML rather than the expected binary content. In that case
// read the body as text, report it, and return.
if status_code != 200 {
let sb_error = chilkat::StringBuilder::new();
if rest.read_resp_sb(&sb_error).is_err() {
println!("{}", rest.last_error_text());
return;
}
println!("Request failed with status code {}", status_code);
println!("{}", sb_error.get_as_string().unwrap_or_default());
return;
}
// The status code is 200. Read the response body into a Stream. Here the stream's sink is a local
// file, which is appropriate for large or binary responses.
let resp_stream = chilkat::Stream::new();
resp_stream.set_sink_file("qa_output/image.png");
// If the 2nd argument is true and the response is textual, the stream's character set is set from
// the response Content-Type charset. It has no effect for binary responses.
let b_auto_set_charset = true;
if rest.read_resp_body_stream(&resp_stream, b_auto_set_charset).is_err() {
println!("{}", rest.last_error_text());
return;
}
println!("Response body written to the stream sink.");