Tuesday, 8 July 2014

how to download an xml webpage which is a response of google script URL



I am writing a client application which suppose to download a response from a given URL every 5 mins.


The URL is a link to Google script with some input (appended in URL) and script is returning a xml webpage and URL is also getting changed for the response. MY Client Application requires to hit the URL with different inputs and store the xml file.


My code actually downloading the html source code of the page.


Any help is highly appreciated.


i have also seen link How to read XML response from a URL in java? but it was not useful.


Code which i have written are*/



public void startCollecting(String targetDir, URL url) throws IOException{
Long timeStamp=System.currentTimeMillis();
String resourcePath = targetDir + timeStamp.toString();
File outputFile = new File(resourcePath);
FileUtils.copyURLToFile(url, outputFile,20000,30000);

}


/*Ussing Apache HTTPConnection */



HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
int responseCode = httpConn.getResponseCode();
Long timeStamp=System.currentTimeMillis();
String fileName = saveDir + timeStamp.toString();

// always check HTTP response code first
if (responseCode == HttpURLConnection.HTTP_OK) {

String disposition = httpConn.getHeaderField("Content-Disposition");
String contentType = httpConn.getContentType();
int contentLength = httpConn.getContentLength();

System.out.println("Content-Type = " + url.openConnection());
System.out.println("Content-Disposition = " + disposition);
System.out.println("Content-Length = " + contentLength);
System.out.println("fileName = " + fileName);

// opens input stream from the HTTP connection
InputStream inputStream = httpConn.getInputStream();
String saveFilePath = saveDir;

// opens an output stream to save into file
FileOutputStream outputStream = new FileOutputStream(saveFilePath);

int bytesRead = -1;
byte[] buffer = new byte[BUFFER_SIZE];
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}

outputStream.close();
inputStream.close();

System.out.println("File downloaded");
} else {
System.out.println("No file to download. Server replied HTTP code: " + responseCode);
}
httpConn.disconnect();

No comments:

Post a Comment