FileNotFoundExcption on connection.getInputStream(); line on API level less than 23 - android

I am downloading HTML file from server using URLConnection but I am getting FileNotFoundException. My path is correct. Using same code same file is downloaded on android of API level 25 but on API level less than it is not downloading. Also connection.getContentLength(); is giving 311 value always. I am not getting any answer to solve this. I am hereby adding my code.
My class file code is
String HomeScreenResourcefilename = WebHomescreenResObj.getString("FileName");
int ProductTargetID = WebHomescreenResObj.getInt("ProductTargetID");
String WebURL_Part1 = context.getResources().getString(R.string.FileDownloadRootPath)+"/ExhibitorData/";
String WebURL_Part2 = GlobalVariables.tradeShowName+" - "+GlobalVariables.exhibitorName+"/HTMLHomeScreen/"+ProductTargetID +"/"+HomeScreenResourcefilename;
String WebURL = WebURL_Part1 + WebURL_Part2;
try {
URL url = new URL(WebURL);
File file = new File(context.getFilesDir(), HomeScreenResourcefilename);
URLConnection connection = url.openConnection();
connection.connect();
FileOutputStream fileOutput = new FileOutputStream(file);
//Stream used for reading the data from the internet
InputStream inputStream = connection.getInputStream();
byte[] buffer = new byte[1024];
int bufferLength = 0;
while ((bufferLength = inputStream.read(buffer)) > 0) {
fileOutput.write(buffer, 0, bufferLength);
}
fileOutput.close();
} catch (Exception e1) {
e1.printStackTrace();
LogE("error in 14 :"+e1);
}

Use HttpURLConnection and then connection.getResponseCode() to get the status code. If it is greater than 400, that might be the reason.
Update: Use url encoding.

Related

how to know the size of downloaded file before and after the download in android

i m making an android app to download pdf files from android and then saving them in a folder in internal or external memory.but sometime due to bad internet connection download stops without finshing .like file size is 1.1mb and its only downloaded upto 750kb. now the problem is whether file fully download or not my app showing it as download but in real it is not.so i want to know the exact size of file befor and after download so that i can found whether file is completely download or not.and want to restart the download.
can anybody help me........
my code
String DownloadUrl = "http://www.example.com/books/"+book_name;
String fileName = book_name;
URL url = new URL(DownloadUrl);
//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 = new File("/storage/emulated/0/documents/docx/stuff/");
File SDCardRoot = new File(Environment.getExternalStorageDirectory()+File.separator+"MybookStore/paper/paperStuff/documents/docx/other/stuff/");
//create a new file, specifying the path, and the filename
//which we want to save the file as.
File file = new File(SDCardRoot,fileName);
String file_size = Long.toString(file.length()/1024);
int size_file=Integer.parseInt(file_size);
//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;
int progress=(int)(downloadedSize*100/totalSize);
//this is where you would do something to report the prgress, like this maybe
//updateProgress(downloadedSize, totalSize);
}
my code
Any reasonable server response header will include a Content-Length key, which will hopefully denote the full length of the resource you’re trying to download.
With that in mind, here's a quick example:
HttpURLConnection connection = null;
InputStream input = null;
OutputStream output = null;
try {
final URL url = new URL(resourceUrl);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
final int length = connection.getContentLength();
int downloaded = 0;
input = url.openStream();
output = new FileOutputStream(targetFile);
final byte[] buffer = new byte[BUFFER_SIZE];
int read;
while ((read = input.read(buffer)) != -1) {
output.write(buffer, 0, read);
downloaded += read;
}
if (downloaded == length) {
// The file was successfully downloaded.
} else {
// The file was not fully downloaded.
}
} catch (IOException e) {
// Handle exception.
} finally {
// Close resources.
}

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

FileNotFoundException with HttpURLConnection in Android

URL url = new URL(path);
HttpURLConnection c = (HttpURLConnection) url.openConnection();
c.setRequestMethod("GET");
c.setDoOutput(true);
c.connect();
String PATH = "/mnt/sdcard/Android/";
File file = new File(PATH);
file.mkdirs();
File outputFile = new File(file, "version.txt");
if(outputFile.exists()){
outputFile.delete();
}
FileOutputStream fos = new FileOutputStream(outputFile);
InputStream is = c.getInputStream();
byte[] buffer = new byte[1024];
int len1 = 0;
while ((len1 = is.read(buffer)) != -1) {
fos.write(buffer, 0, len1);
}
fos.close();
is.close();
Exception caught: java.io.FileNotFoundException http://192.168.2.143/version.txt, where path="http://192.168.2.143/version.txt", I use browser in my device to open http://192.168.2.143/version.txt, can be opened. I have INTERNET permission in my manifest. Any idea?
It's the same problem I was having:
HttpUrlConnection returns FileNotFoundException if you try to read the getInputStream() from the connection.
You should instead use getErrorStream() when the status code is higher than 400.
More than this, please be careful since it's not only 200 to be the success status code, even 201, 204, etc. are often used as success statuses.
Here is an example of how I went to manage it
... connection code code code ...
// Get the response code
int statusCode = connection.getResponseCode();
InputStream is = null;
if (statusCode >= 200 && statusCode < 400) {
// Create an InputStream in order to extract the response object
is = connection.getInputStream();
}
else {
is = connection.getErrorStream();
}
... callback/response to your handler....
In this way, you'll be able to get the needed response in both success and error cases.
Hope this helps!
Try this to read file over the internet: Reading Text File From Server on Android
I'm not sure you can use File.

Zip file download in android

I have an app to download zip file content from drop box (which is publicly shared path). i wrote download code using HttpURLConnection but its not working as intended and instead is downloading a small portion (after download zip file showing 31 kb but its original size is 3mb). i am attching my code. please help me to solve this.
URL url = new URL("drop box public share url");
//create the new connection
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setAllowUserInteraction(false);
urlConnection.setInstanceFollowRedirects(true);
urlConnection.setConnectTimeout(5 * 1000);
urlConnection.setRequestMethod("GET");
urlConnection.setDoOutput(true);
urlConnection.setDoInput(true);
urlConnection.connect();
File SDCardRoot = Environment.getExternalStorageDirectory();
File file = new File(SDCardRoot,"/download/sample.zip");
FileOutputStream fileOutput = new FileOutputStream(file);
InputStream inputStream = urlConnection.getInputStream();
int totalSize = urlConnection.getContentLength();
int downloadedSize = 0;
//create a buffer...
byte[] buffer = new byte[1024];
int bufferLength = 0;
while ( (bufferLength = inputStream.read(buffer)) > 0 ) {
fileOutput.write(buffer, 0, bufferLength);
downloadedSize += bufferLength;
onProgressUpdate(downloadedSize, totalSize);
}
//close the output stream when done
fileOutput.close();
inputStream.close();
It seems that the method call:
setDoOuput(true);
makes the request a POST (see
What exactly does URLConnection.setDoOutput() affect?)
Removing it seems to fix the issue.
Try to use plain URLConnection not HttpURLConnection. And see the output.

Categories

Resources