Thursday, November 13, 2014

Writing Data From REST to a File



private static void doHttpGet(HttpGet request, String inputFile) {
OutputStream outputStream = null;
File file = null;
InputStream content = null;
CloseableHttpClient httpClient = null;
try {


httpClient = getHTTPClient();

HttpResponse response = httpClient.execute(request);
HttpEntity entity = response.getEntity();
content = entity.getContent();

if (content != null) {
file = new File(inputFile);
System.out.print(file.getAbsolutePath());
outputStream = new FileOutputStream(file);

int read = 0;
byte[] bytes = new byte[1024];

while ((read = content.read(bytes)) != -1) {
outputStream.write(bytes, 0, read);
}
}
// Ensure it is fully consumed
EntityUtils.consume(entity);

} catch (IOException e) {
e.printStackTrace();
} finally {
if (outputStream != null) {
try {
outputStream.close();
outputStream = null;
content.close();
httpClient.close();
httpClient = null;
content = null;
} catch (IOException e) {
e.printStackTrace();
}

}
}
}




private static CloseableHttpClient  getHTTPClient() {
RequestConfig.Builder requestBuilder = RequestConfig.custom();
requestBuilder = requestBuilder.setConnectTimeout(180000); //3 * 60 * 1000
   requestBuilder = requestBuilder.setConnectionRequestTimeout(180000);//3 * 60 * 1000
   requestBuilder = requestBuilder.setSocketTimeout(180000);//3 * 60 * 1000
 

HttpClientBuilder  builder = HttpClientBuilder.create();     
builder.setDefaultRequestConfig(requestBuilder.build());

return builder.build();
}

No comments:

Post a Comment