Java
Chilkat2 Java
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 Java Downloads
import com.chilkatsoft.chilkat2.ChilkatException;
import com.chilkatsoft.chilkat2.Rest;
import com.chilkatsoft.chilkat2.Stream;
import com.chilkatsoft.chilkat2.Url;
public class ChilkatExample {
public static void main(String[] args) {
// This example requires the Chilkat API to have been previously unlocked.
// See Global Unlock Sample for sample code.
Rest rest = new Rest();
Url 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
boolean bAutoReconnect = true;
try {
rest.connect(url.getHost(), url.getPort(), url.getSsl(), bAutoReconnect);
rest.addQueryParam("name", "John");
rest.addQueryParam("age", "33");
// Send the HTTP POST.
rest.sendReqFormUrlEncoded("POST", url.getPath());
} catch (ChilkatException e) {
System.out.println(e.getLastErrorText());
return;
}
// Read the response header.
int responseStatusCode = rest.readResponseHeader();
if (responseStatusCode < 0) {
System.out.println(rest.getLastErrorText());
return;
}
System.out.println("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) {
Stream bodyStream = new Stream();
// The stream's sink will be a file.
bodyStream.setSinkFile("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 {
rest.readRespBodyStream(bodyStream, true);
} catch (ChilkatException e) {
System.out.println(e.getLastErrorText());
return;
}
System.out.println("Successfully streamed the response to a file.");
} else {
String errResponse = null;
try {
errResponse = rest.readRespBodyString();
System.out.println(errResponse);
} catch (ChilkatException e) {
System.out.println(e.getLastErrorText());
}
}
}
}