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

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);
}

Related

Hey! I wanna save in ExternalStoragePublic file which I receive from the internet, but I really stuck. May you help me with code?

url = "http://r8---sn-03guxaxjvh-3c2r.googlevideo.com/videoplayback?sparams=dur%2Cei%2Cid%2Cinitcwndbps%2Cip%2Cipbits%2Citag%2Clmt%2Cmime%2Cmm%2Cmn%2Cms%2Cmv%2Cpl%2Cratebypass%2Csource%2Cexpire&mn=sn-03guxaxjvh-3c2r&ip=212.113.45.145&source=youtube&mm=31&mv=m&mime=video%2Fmp4&mt=1505092537&ipbits=0&initcwndbps=685000&dur=2223.728&id=o-AM9pUI9o5NsL8P-jGi5-w17xJOo-VVQ-TrWlMZaV17cp&key=yt6&lmt=1499875418101464&signature=4AACC08B22F2F1F343F5A044188CD751A6AD2F08.A7BA661DDC07639A7E414169226A35A700888AF3&ms=au&ei=HOS1WezYFZfq7gT40rnoAw&itag=22&pl=22&expire=1505114236&ratebypass=yes&title=Gothic+Rock+-+Dark+Music";
streamPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
try {
streamPlayer.setDataSource(url);
} catch (IOException e) {
e.printStackTrace();
}
try {
streamPlayer.prepare();
} catch (IOException e) {
e.printStackTrace();
}
streamPlayer.start();`
my question is how to store on a device my streamPlayer object?
Try this
private static void downloadFile(String url, File outputFile) {
try {
URL u = new URL(url);
URLConnection conn = u.openConnection();
int contentLength = conn.getContentLength();
DataInputStream stream = new DataInputStream(u.openStream());
byte[] buffer = new byte[contentLength];
stream.readFully(buffer);
stream.close();
DataOutputStream fos = new DataOutputStream(new
FileOutputStream(outputFile));
fos.write(buffer);
fos.flush();
fos.close();
} catch(FileNotFoundException e) {
return; // swallow a 404
} catch (IOException e) {
return; // swallow a 404
}
}

How to parse fileinputstream returned from ResponceEntity.getbody() to write into a file in android

I want to download file(.docx,.pdf,image,or any type) from server.I am using spring-mvc REST API.By Using Resttemplate.exchange(...) i got Response from server in the form of stream but i am unable to parse it.So how should i do that and write into file?
File Return code (server) :
public ResponseEntity<?> downloadFile(..){
if (downloadFile.exists()) {
FileInputStream fileInputStream = new FileInputStream(downloadFile);
return ResponseEntity.ok()
.contentLength(downloadFile.length())
.contentType(MediaType.parseMediaType("application/octet-stream"))
.body(newInputStreamResource(fileInputStream));}
else {
return responseEntity.status(HttpStatus.NOT_FOUND)
.body(ErrorMsgWebapiUtil.AUTHORIZED_USER);
}
}
Response from Server:
<200 OK,PNG
������
IHDR����8����û������Þ¢ø������sBIT3���� ��IDATxíÝ?'T����pþÖé������T*����#8B����G¨������á���� ¡����#T����p
����P����Â*����#8B����G¨������á���� ¡����#T����p
����P����Â*����#8B����G¨������á���� ¡����#T����p
����P����Â*����#8B����G¨������á���� ¡����#T����p
����P����Â*����#8B����G¨������á���� ¡����óÿ��0\§ÁzõK��������IEND®B`
Code At my Android (client) :
try {
mRespEntity = mRestTemplate.exchange(strFinal, HttpMethod.POST, mRequestEntity, String.class);
mResponseCode = mRespEntity.getStatusCode().toString();
if (mResponseCode.equals("200")) {
String outdir = "sdcard/downloads/";
int length = Integer.parseInt(mRespEntity.getHeaders().getContentLength() + "");
inputStream = new BufferedInputStream((InputStream) mRespEntity.getBody()); //Here it Throughs Exception:java.lang.String cannot be cast to java.io.InputStream
byte[] buffer = new byte[length];
int read = 0;
File dFile = new File(outdir, filename);
fos = new DataOutputStream(new FileOutputStream(dFile));
while ((read = inputStream.read(buffer)) != -1) {
fos.write(buffer, 0, read);
}
}
} catch (Exception e) {
if (e != null) {
e.printStackTrace();
Log.e(TAG, "getFileFolderSyncData() Error:" + e.getMessage());
return false;
}
} finally {
// resetSSLFactory();
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (fos != null) {
try {
// outputStream.flush();
fos.flush();
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
At Line inputStream = new BufferedInputStream((InputStream) mRespEntity.getBody()); here it through exception :"java.lang.String cannot be cast to java.io.InputStream"
Got solution...
public String FileDownload(...){
String url = ....;
String res = ...;
String outdir = ...;
File outputFile = new File(outdir, filename);
BufferedInputStream in = null;
FileOutputStream fout = null;
try {
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("POST");
con.setRequestProperty("param1", value);//post parameters
String urlParameters = ...;
// Send post request
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(urlParameters);
wr.flush();
wr.close();
int responseCode = con.getResponseCode();
if (responseCode == 200) {
in = new BufferedInputStream(con.getInputStream());
fout = new FileOutputStream(outputFile);
final byte data[] = new byte[1024];
int count;
while ((count = in.read(data, 0, 1024)) != -1) {
fout.write(data, 0, count);
}
res = "true";
} else {
res = con.getResponseMessage();
}
} catch (Exception e) {
e.printStackTrace();
Log.e(TAG, "Exception in file Download:" + e.getMessage());
res = "false";
} finally {
try {
if (in != null) {
in.close();
}
if (fout != null) {
fout.close();
}
res = "true";
} catch (IOException e) {
e.printStackTrace();
res = "false";
}
}
return res;
}

HttpURLConnection java.io.FileNotFoundException in android 5.0.2

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.

How to receive data from the server?

I am trying to fetchg data from server like MP3 files, video files, etc. in my application. The application should show the list of video files received from the server.
How can I do this?
/** this function will download content from the internet */
static int writeData(String fileurl, boolean append, String path,
String filename, Activity mContext) throws CustomException {
URL myfileurl = null;
ByteArrayBuffer baf = null;
HttpURLConnection conn = null;
String mimeType="";
final int length;
try {
myfileurl = new URL(fileurl);
} catch (MalformedURLException e) {
e.printStackTrace();
}
try {
conn = (HttpURLConnection) myfileurl
.openConnection();
conn.setDoInput(true);
conn.connect();
conn.setConnectTimeout(100000);
length = conn.getContentLength();
mimeType=conn.getContentType().toString();
System.out.println("Extension..."+mimeType);
if(mimeType.equalsIgnoreCase("application/vnd.adobe.adept+xml") || mimeType.equalsIgnoreCase("text/html; charset=utf-8"))
return 0;
if (length > 0) {
InputStream is = conn.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
baf = new ByteArrayBuffer(1000);
int current = 0;
while ((current = bis.read()) != -1) {
try {
baf.append((byte) current);
mBufferError=false;
} catch (Exception e){
// TODO: handle exception
mBufferError=true;
e.printStackTrace();
throw new CustomException("### memory problem ", "Buffer Error");
}
}
}
} catch (IOException e) {
mBufferError=true;
e.printStackTrace();
}
try{
if(conn.getResponseCode()==200 && mBufferError==false)
{
path = path + "/" + filename;
boolean appendData = append;
FileOutputStream foutstream;
File file = new File(path);
boolean exist = false;
try {
if (appendData)
exist = file.exists();
else
exist = file.createNewFile();
} catch (IOException e) {
try {
return 1;
} catch (Exception err) {
Log.e("SAX", err.toString());
}
}
if (!appendData && !exist) {
} else if (appendData && !exist) {
} else {
try {
foutstream = new FileOutputStream(file, appendData);
foutstream.write(baf.toByteArray());
foutstream.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}catch (Exception e) {
// TODO: handle exception
throw new CustomException("### I/O problem ", "I/O Error");
}
return 1;
}
once download complete search the file with extension(.3gp) for video
hope it helps
Check this link,
https://stackoverflow.com/search?q=how+to+download+mp3+%2Cvideos+from+server+in+android
Try this code
url = "your url name+filename.jpg,mp3,etc..."
FileName = "/sdcard/savefilename" // save in your sdcard
try{
java.io.BufferedInputStream in = new java.io.BufferedInputStream(new java.net.URL(url).openStream());
java.io.FileOutputStream fos = new java.io.FileOutputStream(FileName);
java.io.BufferedOutputStream bout = new BufferedOutputStream(fos,1024);
byte[] data = new byte[1024];
int x=0;
while((x=in.read(data,0,1024))>=0){
bout.write(data,0,x);
}
fos.flush();
bout.flush();
fos.close();
bout.close();
in.close();
}
catch (Exception ex)
{
}
and after you want to use MediaPlayer
and create object of mediaplayer in your activity
and play.
mp.reset();
mp.start();

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