HttpURLConnection java.io.FileNotFoundException in android 5.0.2 - android

i am using below code for downloading pdf file from server and store into sdcard. its running fine on android 4.4 device. while its not working on android 5.0.2 device.
public static String downloadFile(String fileUrl, File directory){
try {
URL url = new URL(fileUrl);
HttpURLConnection urlConnection = (HttpURLConnection)url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setDoOutput(false);
urlConnection.connect();
InputStream inputStream = urlConnection.getInputStream();
FileOutputStream fileOutputStream = new FileOutputStream(directory);
int totalSize = urlConnection.getContentLength();
byte[] buffer = new byte[MEGABYTE];
int bufferLength = 0;
while((bufferLength = inputStream.read(buffer))>0 ){
fileOutputStream.write(buffer, 0, bufferLength);
}
fileOutputStream.close();
result = "true";
} catch (FileNotFoundException e) {
e.printStackTrace();
result = "false";
} catch (MalformedURLException e) {
e.printStackTrace();
result = "false";
} catch (IOException e) {
e.printStackTrace();
result = "false";
}
return result;
}
On Line: InputStream inputStream = urlConnection.getInputStream(); i got java.io.FileNotFoundException error.
i tried so many things but didnt work. help me to solved this bug.

Related

How can I download Image File from an URL to ByteArray?

following is my code:
private byte[] downloadImage(String image_url) {
byte[] image_blob = null;
URL _image_url = null;
HttpURLConnection conn = null;
InputStream inputStream = null;
try {
_image_url = new URL(image_url);
} catch (MalformedURLException e) {
e.printStackTrace();
}
try {
conn = (HttpURLConnection) _image_url.openConnection();
} catch (IOException e) {
e.printStackTrace();
}
conn.setDoInput(true);
try {
conn.connect();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
conn.setUseCaches(false);
try {
inputStream = conn.getInputStream();
inputStream.read(image_blob);
} catch (IOException ex) {
ex.printStackTrace();
} finally {
try {
inputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
conn.disconnect();
}
return image_blob;
}
What I am trying to do is to get the byte array of an Image. Use it in a parcel to transfer it to another activity.
Using this code a NullPointerException is reported. Can any one say what is wrong?
You might want to try it like this:
DefaultHttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet(imageUrl);
HttpResponse response = client.execute(request);
HttpEntity entity = response.getEntity();
int imageLength = (int)(entity.getContentLength());
InputStream is = entity.getContent();
byte[] imageBlob = new byte[imageLength];
int bytesRead = 0;
while (bytesRead < imageLength) {
int n = is.read(imageBlob, bytesRead, imageLength - bytesRead);
if (n <= 0)
; // do some error handling
bytesRead += n;
}
And by the way: The NullPointerException is caused because image_blob is null. You need to allocate the array first before you can read data into it.
Rather then sending image, you can send path of image which is download in cache. You can just use this methods to proive image path and download image into local path.
private String createLocal(String surl) {
URL url;
try {
url = new URL(surl);
String tempname=String.valueOf(surl.hashCode());
File root=getCacheDir();
File localfile=new File(root.getAbsolutePath()+"/"+tempname);
localfile.deleteOnExit();
if(!localfile.exists()){
InputStream is=url.openStream();
OutputStream os = new FileOutputStream(localfile);
CopyStream(is, os);
os.close();
}
return localfile.getAbsolutePath();
} catch (Exception e){
return null;
}
}
public static void CopyStream(InputStream is, OutputStream os) {
final int buffer_size=1024;
try {
byte[] bytes = new byte[buffer_size];
for(;;) {
int count=is.read(bytes, 0, buffer_size);
if(count == -1)
break;
os.write(bytes, 0, count);
}
}
catch(Exception ex){}
}
Your byte[] image_blob is null,you must new enough space like that before you use it:
image_blob = new byte[enough];
inputStream.read(image_blob);
public static byte[] getByteArray(String url) throws IOException {
InputStream inputStream = (InputStream) new URL(url).getContent();
return IOUtils.toByteArray(inputStream);
}

android download large file

i have various files need to download from web into phone
I have done the code but the code only can let me download with the small size such as picture/photo. A large file like .apk which cost around 2mb to >100mb will failed me.
below is the code:
final ProgressDialog progress=ProgressDialog.show(this, "Please wait", "Loading ...", true);
new Thread()
{
public void run()
{
try {
URL url = new URL("http://www.domain.com/apk/Gmail.apk");
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setDoOutput(true);
urlConnection.connect();
File SDCardRoot = Environment.getExternalStorageDirectory();
File file = new File(SDCardRoot, "Gmail.apk");
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);
//downloadedSize += bufferLength;
}
fileOutput.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
progress.dismiss();
}
}.start();

"decoder->decode returned false" when download image and view it in ImageView

I try to use FlushedInputStream : Android decoder->decode returned false for Bitmap download
but nothing change, because i use: BitmapFactory.decodeFile(path_of_my_downloaded_file), not use BitmapFactory.decodeStream
This is my code of download file:
public static boolean downloadFile(String url, String dir, String name){
Log.i("Start Downloading ", "=");
// Create download folder:
File f = new File(dir);
if(!f.exists()){
f.mkdirs();
}
try {
File fTo = new File(dir, name);
URL downloadUrl = new URL(url);
//create the new connection
HttpURLConnection urlConnection = (HttpURLConnection) downloadUrl.openConnection();
//set up some things on the connection
urlConnection.setRequestMethod("GET");
urlConnection.setDoOutput(true);
//and connect!
urlConnection.connect();
FlushedInputStream in = new FlushedInputStream(downloadUrl.openStream());
// in = new FlushedInputStream(in);
byte[] buffer= new byte[4096];
// Write file to toFolder
FileOutputStream os = new FileOutputStream(fTo);
try {
do{
int numread = in.read(buffer);
if (numread <= 0) {
break;
}
os.write(buffer, 0, numread);
}while(true);
} catch (ConnectTimeoutException e) {
e.printStackTrace();
return false;
}
if (os != null) {
os.close();
}
if (in != null) {
in.close();
}
} catch (IOException e) {
Log.e("Error reading file", e.toString());
return false;
}
return true;
}
And this is my code to set Bitmap to ImageView:
Bitmap bitmap = BitmapFactory.decodeFile(my_file);
mImageView.setImageBitmap(bitmap);
I always have "decoder->decode returned false"
Note: I have to download this image first.
This is the problems of image.

Downloading a file from HTTP connection which redirect to HTTPS connection

I am using Dropbox in my project to get tiny url from dropbox which is like http://www.db.tt/xyzabc.
When I try to download the file in HTC My touch my code works fine, but if I try in Motorola Atrix it throws exception unknown host db.tt.
Actually first I have url like http://www.db.tt/xyzabc which is HTTP url I open it than I get exception and in exception I get actual url to file which contain file and is HTTPS url in exception. I start downloading file here is my code which work for me:
public static void fileUrl(String fAddress, String localFileName,
String destinationDir) {
OutputStream outStream = null;
URLConnection uCon = null;
InputStream is = null;
try {
URL url;
byte[] buf;
int ByteRead, ByteWritten = 0;
url = new URL(fAddress);
outStream = new BufferedOutputStream(new FileOutputStream(
destinationDir + localFileName));
try {
// Here i have "http://www.db.tt/xyzabc"
// after i hit url i get exception and in exception that
// FileNotFoundException at https://www.dropbox.com/abcxyz
// i get actual actual url i parse that exception and
//retrive https://www.dropbox.com/xyzabc(actual url)
// but in motorolla atrix instead of that url i get
// unknownhost exception "db.tt"
uCon = url.openConnection();
// uCon.connect();
is = uCon.getInputStream();
} catch (Exception e) {
url = new URL(e.getMessage().substring(
e.getMessage().indexOf("https"),
e.getMessage().length()));
outStream = new BufferedOutputStream(new FileOutputStream(
destinationDir + localFileName));
uCon = url.openConnection();
is = uCon.getInputStream();
}
buf = new byte[size];
while ((ByteRead = is.read(buf)) != -1) {
outStream.write(buf, 0, ByteRead);
ByteWritten += ByteRead;
}
System.out.println("Downloaded Successfully.");
System.out.println("File name:\"" + localFileName
+ "\"\nNo ofbytes :" + ByteWritten);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
is.close();
outStream.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
ok after few attempt i made it solve my self and here is the solution will be helpfull if someone got same problem it requires some error handling and modification according to need
After seeing class heirarchy of Connection i found that HttpsURLConnection is child of HttpURLConnection and HttpURLConnection is child of UrlConnection so i i used HTTPConnection instead of UrlConnection and as HttpsUrlConnection is concrete for HttpsUrlConnection it solved my problem
i continue iterating till i get Https url after redirect
public static void fileUrl(String fAddress, String localFileName,
String destinationDir) {
OutputStream outStream = null;
URLConnection uCon = null;
HttpURLConnection mHttpCon;
InputStream is = null;
try {
URL url;
byte[] buf;
int ByteRead, ByteWritten = 0;
url = new URL(fAddress);
outStream = new BufferedOutputStream(new FileOutputStream(
destinationDir + localFileName));
try {
mHttpCon = (HttpURLConnection) url.openConnection();
while (!url.toString().startsWith("https")) {
mHttpCon.getResponseCode();
url = mHttpCon.getURL();
mHttpCon = (HttpURLConnection) url.openConnection();
}
is = mHttpCon.getInputStream();
} catch (Exception e) {
e.printStackTrace();
// url = new URL(e.getMessage().substring(
// e.getMessage().indexOf("https"),
// e.getMessage().length()));
// outStream = new BufferedOutputStream(new FileOutputStream(
// destinationDir + localFileName));
//
// uCon = url.openConnection();
// is = uCon.getInputStream();
}
buf = new byte[size];
while ((ByteRead = is.read(buf)) != -1) {
outStream.write(buf, 0, ByteRead);
ByteWritten += ByteRead;
}
System.out.println("Downloaded Successfully.");
System.out.println("File name:\"" + localFileName
+ "\"\nNo ofbytes :" + ByteWritten);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
is.close();
outStream.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
public static void fileDownload(String fAddress, String destinationDir) {
int slashIndex = fAddress.lastIndexOf('/');
int periodIndex = fAddress.lastIndexOf('.');
String fileName = fAddress.substring(slashIndex + 1);
if (periodIndex >= 1 && slashIndex >= 0
&& slashIndex < fAddress.length() - 1) {
fileUrl(fAddress, fileName, destinationDir);
} else {
System.err.println("path or file name.");
}
}
This answer works - to an extent. I have a similar solution here
There is still a problem with Dropbox short hyperlinks on Atrix. They redirect from http to https but NOT to the required file, instead I get a whole lot of html from inside Dropbox.

Android Inputstream.read problem on Gingerbread (while downloading)

I didn't find any question like this here.
Yesterday I finally got Gingerbread 2.3.4 on my Nexus One. When I opened my application (basically loads an XML Feed into a ListView) again, it got stuck while downloading.
It seems that InputStream stream; -> stream.read(buffer); doesn't return -1 any more, when it's finished.
The Code ist nearly the same from here Download Progress
Here's my code:
public InputStream getInputStreamFromURL(String urlString, DownloadProgressCallback callback)
throws IOException, IllegalArgumentException
{
InputStream in = null;
conn = (HttpURLConnection) new URL(urlString).openConnection();
fileSize = conn.getContentLength();
out = new ByteArrayOutputStream((int) fileSize);
conn.connect();
stream = conn.getInputStream();
// loop with step 1kb
while (status == DOWNLOADING) {
byte buffer[];
if (fileSize - downloaded > MAX_BUFFER_SIZE) {
buffer = new byte[MAX_BUFFER_SIZE];
} else {
buffer = new byte[(int) (fileSize - downloaded)];
}
int read = stream.read(buffer);
if (read == -1) {
break;
}
// writing to buffer
out.write(buffer, 0, read);
downloaded += read;
// update progress bar
callback.progressUpdate((int) ((downloaded / fileSize) * 100));
}// end of while
if (status == DOWNLOADING) {
status = COMPLETE;
}
in= (InputStream) new ByteArrayInputStream(out.toByteArray());
// end of class DownloadImageTask()
return in;
}
The problem basically is that when the download finishes, stream.read(buffer) returns 0 instead of -1. When I change
if (read == -1) {
break;
}
to 0 or
if (fileSize == downloaded) {
break;
}
I get ParseExceptions (ExpatParser) on my MainActivity.
On 2.2 it runs really perfect.
I cleared the app cache and tried a few other things already, but I'm really stuck now.
I hope that someone can help me. :)
UPDATE:
That's awesome, you're the man, Guillaume. :)
Thank you very much, that saved my evening! :)
Your Code for my needs here:
public InputStream getStreamFromURL(String urlString, DownloadProgressCallback callback){
// initialize some timeouts
HttpParams httpParameters = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParameters,3000);
// create the connection
URL url;
try {
url = new URL(urlString);
URLConnection connection = url.openConnection();
HttpURLConnection httpConnection = (HttpURLConnection) connection;
// connection accepted
if(httpConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
int size = connection.getContentLength();
int index = 0;
int current = 0;
InputStream input = connection.getInputStream();
BufferedInputStream buffer = new BufferedInputStream(input);
byte[] bBuffer = new byte[1024];
out = new ByteArrayOutputStream((int) size);
while((current = buffer.read(bBuffer)) != -1) {
out.write(bBuffer, 0, current);
index += current;
callback.progressUpdate((index/size)*100);
}
out.close();
}
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return (InputStream) new ByteArrayInputStream(out.toByteArray());
}
This code work on my 2.3.4 Nexus One :
try {
// initialize some timeouts
HttpParams httpParameters = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParameters, 3000);
// create the connection
URL url = new URL(toDownload);
URLConnection connection = url.openConnection();
HttpURLConnection httpConnection = (HttpURLConnection) connection;
// connection accepted
if (httpConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
try {
file = new File(destination);
// delete the file if exists
file.delete();
} catch (Exception e) {
// nothing
}
int size = connection.getContentLength();
int index = 0;
int current = 0;
try {
file = new File(destination);
file.delete();
FileOutputStream output = new FileOutputStream(file);
InputStream input = connection.getInputStream();
BufferedInputStream buffer = new BufferedInputStream(input);
byte[] bBuffer = new byte[10240];
while ((current = buffer.read(bBuffer)) != -1) {
if (isCancelled()) {
file.delete();
break;
}
try {
output.write(bBuffer, 0, current);
} catch (IOException e) {
e.printStackTrace();
}
index += current;
publishProgress(index / (size / 100));
}
output.close();
} catch (SecurityException se) {
se.printStackTrace();
return 1;
} catch (FileNotFoundException e) {
e.printStackTrace();
return 1;
} catch (Exception e) {
e.printStackTrace();
return 2;
}
return 0;
}
// connection refused
return 2;
} catch (IOException e) {
return 2;
}

Categories

Resources