React Native
React Native
HTTP POST and Stream Response to File
See more REST Examples
Demonstrates how to send an HTTP POST and stream the response body directly to a file.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();
const url = new Url();
// This URL will emit a response that echos the query params (name and age)
url.parseUrl('https://www.chilkatsoft.com/readPost.asp');
// 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;
}
rest.addQueryParam('name', 'John');
rest.addQueryParam('age', '33');
// Send the HTTP POST.
try {
await rest.sendReqFormUrlEncodedAsync('POST', 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/out.txt';
// 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 streamed the response to a file.');
} else {
try {
const errResponse = await rest.readRespBodyStringAsync();
console.log(errResponse);
} catch {
console.log(rest.lastErrorText);
}
}
}