React Native
React Native
HTTP Download to Stream
See more REST Examples
Demonstrates how to stream the response body directly to a stream, which in this case is to a file stream.Chilkat React Native Downloads
import { Rest, Stream, Url } from '@chilkat/react-native'
async function chilkatExample() {
// This example requires the Chilkat API to have been previously unlocked.
// See Global Unlock Sample for sample code.
const rest = new Rest();
// The URL we want to download is:
// https://github.com/chilkatsoft/OAuth2-CSharp-Desktop/archive/master.zip
const url = new Url();
url.parseUrl('https://github.com/chilkatsoft/OAuth2-CSharp-Desktop/archive/master.zip');
// Connect to the web server
const bAutoReconnect = true;
try {
await rest.connectAsync(url.host, url.port, url.ssl, bAutoReconnect);
} catch {
console.log(rest.lastErrorText);
return;
}
try {
await rest.sendReqNoBodyAsync('GET', url.path);
} catch {
console.log(rest.lastErrorText);
return;
}
// Read the response header.
const responseStatusCode = await rest.readResponseHeaderAsync();
if (responseStatusCode < 0) {
console.log(rest.lastErrorText);
return;
}
console.log(`Response status code = ${responseStatusCode}`);
// We expect a 200 response status if the file data is coming.
// Otherwise, we'll get a string response body with an error message(or no response body).
if (responseStatusCode === 200) {
const bodyStream = new Stream();
// The stream's sink will be a file.
bodyStream.sinkFile = 'qa_output/OAuth2-CSharp-Desktop/archive/master.zip';
// Read the response body to the stream. Given that we've
// set the stream's sink to a file, it will stream directly
// to the file.
try {
await rest.readRespBodyStreamAsync(bodyStream, true);
} catch {
console.log(rest.lastErrorText);
return;
}
console.log('Successfully downloaded the file.');
} else {
try {
const errResponse = await rest.readRespBodyStringAsync();
console.log(errResponse);
} catch {
console.log(rest.lastErrorText);
}
}
}