read the remote xml file in android - android

I have a xml file in remote place.I want to use that xml file in my android project.can anyone give me a example code for this.I am using android 2.2.
P.S : I can access the local xml file which is in /res folder.
I don't know anything about xPath.

try {
//set the download URL, a url that points to a file on the internet
//this is the file to be downloaded
URL url = new URL("http://IP/Downloads/data.xml");
//create the new connection
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
//and connect!
urlConnection.connect();
//set the path where we want to save the file
//in this case, going to save it on the root directory of the
//sd card.
File SDCardRoot = Environment.getExternalStorageDirectory();
//create a new file, specifying the path, and the filename
//which we want to save the file as.
File file = new File(SDCardRoot,"data.xml");
//this will be used to write the downloaded data into the file we created
FileOutputStream fileOutput = new FileOutputStream(file);
//this will be used in reading the data from the internet
InputStream inputStream = urlConnection.getInputStream();
//this is the total size of the file
int totalSize = urlConnection.getContentLength();
progressDialog.setMax(totalSize);
//variable to store total downloaded bytes
int downloadedSize = 0;
//create a buffer...
byte[] buffer = new byte[1024];
int bufferLength = 0; //used to store a temporary size of the buffer
//now, read through the input buffer and write the contents to the file
while ( (bufferLength = inputStream.read(buffer)) > 0 ) {
//add the data in the buffer to the file in the file output stream (the file on the sd card
fileOutput.write(buffer, 0, bufferLength);
//add up the size so we know how much is downloaded
downloadedSize += bufferLength;
}
//close the output stream when done
fileOutput.close();
//catch some possible errors...
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Try this code for downloading your xml file and check this tutorial for reading xml http://www.java-samples.com/showtutorial.php?tutorialid=152

if you are trying to set layout or drawable or style by remote xml , you can't.

Better way to read it in String and do whatever you want to do with it.
public String getXmlFromUrl(String url)
{
String xml = null;
try
{
//default http client
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
System.out.println("URL IN PARSER:==="+url+"====");
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpentity = httpResponse.getEntity();
xml = EntityUtils.toString(httpentity); // I have changed it... because  occur while downloading..
Log.d("response", xml);
}
catch(UnsupportedEncodingException e)
{
e.printStackTrace();
}
catch (ClientProtocolException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
return xml;
}

Related

Android http file transfer using app

I've written the following code to download a file from an url to the external memory in Android application works perfectly.
Now i want to add check authorization before getting its access,how to do this ?
When i enter the url in browser,it asks for username and password
URL url = null;
try {
url = new URL("http://192.168.0.1:4040/usb_dev/usb_a1/New%20folder/ebook-%20sql_serve.doc");
//create the new connection
HttpURLConnection urlConnection = null;
urlConnection = (HttpURLConnection) url.openConnection();
//set up some things on the connection
urlConnection.setRequestMethod("GET");
urlConnection.setDoOutput(true);
//and connect!
//String basicAuth = "Basic " + new String(Base64.encode("admin:".getBytes(), Base64.NO_WRAP ));
// urlConnection.setRequestProperty ("Authorization", basicAuth);
// urlConnection.setConnectTimeout(30000);
// urlConnection.setReadTimeout(30000);
urlConnection.connect();
//set the path where we want to save the file
//in this case, going to save it on the root directory of the
//sd card.
File SDCardRoot = Environment.getExternalStorageDirectory();
//create a new file, specifying the path, and the filename
//which we want to save the file as.
File file = new File(SDCardRoot,"sql.doc");
//this will be used to write the downloaded data into the file we created
FileOutputStream fileOutput = null;
fileOutput = new FileOutputStream(file);
//this will be used in reading the data from the internet
InputStream inputStream = null;
inputStream = urlConnection.getInputStream();
//this is the total size of the file
int totalSize = urlConnection.getContentLength();
//variable to store total downloaded bytes
int downloadedSize = 0;
//create a buffer...
byte[] buffer = new byte[1024];
int bufferLength = 0; //used to store a temporary size of the buffer
//now, read through the input buffer and write the contents to the file
while ( (bufferLength = inputStream.read(buffer)) > 0 ) {
//add the data in the buffer to the file in the file output stream (the file on the sd card
fileOutput.write(buffer, 0, bufferLength);
//add up the size so we know how much is downloaded
downloadedSize += bufferLength;
//this is where you would do something to report the prgress, like this maybe
// updateProgress(downloadedSize, totalSize);
}
//close the output stream when done
fileOutput.close();
} catch (MalformedURLException e1) {
e1.printStackTrace();
} catch (ProtocolException e1) {
e1.printStackTrace();
} catch (FileNotFoundException e1) {
e1.printStackTrace();
}catch (IOException e1) {
e1.printStackTrace();
}

Get files from web service

I have a URL(http://xxx.xxx/api/getFiles) which is returning a JSON response. According to the developer of the API, this link also return files (images, pdf, word, excel, video, etc) that we're going to download to our Android device.
This link returns a file path (e.g. "/File Folder/") and file name (e.g. "Penguins.jpg") that will be used to link the file to the web server but I don't have an idea how to do it.
Are there ways to download it using this API?
JSON response:
{
   "status":"success",
   "count":1,
   "files":[
      {
         "file_code":"2",
         "file_name":"Penguins.jpg",
         "file_type":".jpg",
         "file_path”:”\/File Folder\/“
      }
   ]
}
To download file from url following peice of code can help you:
This code will create connection with url server and download it to specified path:
int downloadedSize = 0;
int totalSize = 0;
try {
URL url = new URL("download file url");
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setDoOutput(true);
//connect
urlConnection.connect();
//set the path where we want to save the file
File SDCardRoot = Environment.getExternalStorageDirectory();
//create a new file, to save the downloaded file
File file = new File(SDCardRoot, "DownloadFileNameWithExtension"); // like test.png
FileOutputStream fileOutput = new FileOutputStream(file);
//Stream used for reading the data from the internet
InputStream inputStream = urlConnection.getInputStream();
//this is the total size of the file which we are downloading
totalSize = urlConnection.getContentLength();
//create a buffer...
byte[] buffer = new byte[1024];
int bufferLength = 0;
while ((bufferLength = inputStream.read(buffer)) > 0) {
fileOutput.write(buffer, 0, bufferLength);
downloadedSize += bufferLength;
}
//close the output stream when complete //
fileOutput.close();
} catch (final MalformedURLException e) {
e.printStackTrace();
} catch (final IOException e) {
e.printStackTrace();
} catch (final Exception e) {
e.printStackTrace();
}
Don't forget to add Internet permission in your manifest:D

File Download over http request failed

In My android Application i have a list of song.User can download any of song from it.
But my problem is when i download a file using http request it return content length = 0 or -1 so i can not download file.
When i use same url in browser then song downloaded completely.
My code to download a song file is -
URL url = new URL(mUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setDoOutput(true);
connection.setConnectTimeout(TimeOut);
connection.setReadTimeout(TimeOut);
connection.connect();
int lenghtOfFile = connection.getContentLength();
and file length is either 0 or -1.
What the problem in my code.
Thanks in advance.
The best way to run an Http Request wheter download or upload is to use AsycTask in order to split the download task from your UI,
try to download your file by putting this code in a method and call it, if your using an AsyncTask you can add a progressBar and update it's progression from the below given code
to update progress uncomment
updateProgress(downloadedSize,totalSize);
try {
//set the download URL, a url that points to a file on the internet
//this is the file to be downloaded
URL url = new URL("File Url");
//create the new connection
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
//set up some things on the connection
urlConnection.setRequestMethod("GET");
urlConnection.setDoOutput(true);
//connect!
urlConnection.connect();
//set the path where we want to save the file
//in this case, going to save it on the root directory of the
//sd card.
File SDCardRoot = Environment.getExternalStorageDirectory();
//create a new file, specifying the path, and the filename
//which we want to save the file as.
File file = new File(SDCardRoot,"song.extension");
//this will be used to write the downloaded data into the file we created
FileOutputStream fileOutput = new FileOutputStream(file);
//this will be used in reading the data from the internet
InputStream inputStream = urlConnection.getInputStream();
//this is the total size of the file
int totalSize = urlConnection.getContentLength();
//variable to store total downloaded bytes
int downloadedSize = 0;
//create a buffer...
byte[] buffer = new byte[1024];
int bufferLength = 0; //used to store a temporary size of the buffer
//now, read through the input buffer and write the contents to the file
while ( (bufferLength = inputStream.read(buffer)) > 0 ) {
//add the data in the buffer to the file in the file output stream (the file on the sd card
fileOutput.write(buffer, 0, bufferLength);
//add up the size so we know how much is downloaded
downloadedSize += bufferLength;
//this is where you would do something to report the prgress, like this maybe
//updateProgress(downloadedSize, totalSize); if your run this code from AsyncTask
}
//close the output stream when done
fileOutput.close();
//catch some possible errors...
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}

Android Get pdf file as a result of httppost

I'm developping an Android application which must download some files from a web service.
Goal
I want download a PDF file from a web service and show it on the phone.
Problem
I'm newbie working with webservices and I'dont have so clear how to get the file and open it.
Here it's my code to date:
public void downloadFile(String username, String password, String filename) {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("username", username));
nameValuePairs.add(new BasicNameValuePair("password", password));
nameValuePairs.add(new BasicNameValuePair("filename", filename));
String output = httpPost(URL_DESCARGAS, nameValuePairs);
}
private String httpPost(String url, List<NameValuePair> nameValuePairs) {
/* Create new HttpClient and Post Header */
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
try {
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs, HTTP.UTF_8));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
/* Get output */
return inputStreamToString(response.getEntity().getContent()).toString();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return "";
}
I don't have to return String of response, but I don't know what I have to do. So how to show pdf that returns web service?
In another activity I have to execute the same but web service returns a .png and I want to show that in an imageview or something like that. It is done in the same way?
Thank you very much. I've searched for a long time but I didn't found anything.
Edit
I've found that url: http://www.androidsnippets.com/download-an-http-file-to-sdcard-with-progress-notification
and I use what it says, but file is not created (I don't see it in sdcard root).
Here is my modified code:
public void downloadFile(String username, String password, String filename) {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("username", username));
nameValuePairs.add(new BasicNameValuePair("password", password));
nameValuePairs.add(new BasicNameValuePair("filename", filename));
HttpResponse response = httpPost(URL_DESCARGAS, nameValuePairs);
HttpEntity entity = response.getEntity();
if (entity != null) {
try {
InputStream inputStream = entity.getContent();
//set the path where we want to save the file
//in this case, going to save it on the root directory of the
//sd card.
File SDCardRoot = Environment.getExternalStorageDirectory();
//create a new file, specifying the path, and the filename
//which we want to save the file as.
File file = new File(SDCardRoot, filename);
//this will be used to write the downloaded data into the file we created
FileOutputStream fileOutput = new FileOutputStream(file);
//create a buffer...
byte[] buffer = new byte[1024];
int bufferLength = 0; //used to store a temporary size of the buffer
//now, read through the input buffer and write the contents to the file
while ( (bufferLength = inputStream.read(buffer)) > 0 ) {
//add the data in the buffer to the file in the file output stream (the file on the sd card
fileOutput.write(buffer, 0, bufferLength);
}
//close the output stream when done
fileOutput.close();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Can you help me? I need to create that file and show it in the phone at the moment.
I've solved that. I forgot to put permissions in AndroidManifest.xml.
Here is my code that gets output of httppost, creates file in SD card and opens it in the pdf viewer that user has installed in device:
Activity class
public void downloadInvoice(View view) {
boolean ok = myApplication.downloadFile("pdf");
if (!ok) {
//If not ok, show error message
} else {
//Open file in pdf viewer that user has in the device
File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath()
+"/"+ myApplication.getActualUser().getActualInvoice().getPdf());
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.fromFile(file));
intent.setType("application/pdf");
startActivity(intent);
}
}
AndroidManifest.xml
...
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
...

how to download file with service in the background?

I'm making a android library app that can download and show special files. now I need to write a service that download file in background! are there samples for services?
and I want to save files in SD, because users can update app and don't should miss downloaded files.
If you have a suggest or opinion for this, write me, please.
try {
URL url = new URL("url from apk file is to be downloaded");
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setDoOutput(true);
urlConnection.connect();
File sdcard = Environment.getExternalStorageDirectory();
File file = new File(sdcard, "filename.ext");
FileOutputStream fileOutput = new FileOutputStream(file);
InputStream inputStream = urlConnection.getInputStream();
byte[] buffer = new byte[1024];
int bufferLength = 0;
while ( (bufferLength = inputStream.read(buffer)) > 0 ) {
fileOutput.write(buffer, 0, bufferLength);
}
fileOutput.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
Permission: To write to external storage, you need to add this permission:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Note: you can use above code to get the file downloaded and saved in the SD card. You can run this code in background using AsysnTask or thread.
This is another sample:
try {
//set the download URL, a url that points to a file on the internet
//this is the file to be downloaded
URL url = new URL("http://somewhere.com/some/webhosted/file");
//create the new connection
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
//set up some things on the connection
urlConnection.setRequestMethod("GET");
urlConnection.setDoOutput(true);
//and connect!
urlConnection.connect();
//set the path where we want to save the file
//in this case, going to save it on the root directory of the
//sd card.
File SDCardRoot = Environment.getExternalStorageDirectory();
//create a new file, specifying the path, and the filename
//which we want to save the file as.
File file = new File(SDCardRoot,"somefile.ext");
//this will be used to write the downloaded data into the file we created
FileOutputStream fileOutput = new FileOutputStream(file);
//this will be used in reading the data from the internet
InputStream inputStream = urlConnection.getInputStream();
//this is the total size of the file
int totalSize = urlConnection.getContentLength();
//variable to store total downloaded bytes
int downloadedSize = 0;
//create a buffer...
byte[] buffer = new byte[1024];
int bufferLength = 0; //used to store a temporary size of the buffer
//now, read through the input buffer and write the contents to the file
while ( (bufferLength = inputStream.read(buffer)) > 0 ) {
//add the data in the buffer to the file in the file output stream (the file on the sd card
fileOutput.write(buffer, 0, bufferLength);
//add up the size so we know how much is downloaded
downloadedSize += bufferLength;
//this is where you would do something to report the prgress, like this maybe
updateProgress(downloadedSize, totalSize);
}
//close the output stream when done
fileOutput.close();
//catch some possible errors...
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}

Categories

Resources