How to receive data from the server? - android

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

Related

Downloaded mp3 file in android throwing IOException

I am using the below code to download an mp3 file from my server to android
public class DownloadService extends IntentService {
private int result = Activity.RESULT_CANCELED;
public static final String RESULT = "result";
public static final String NOTIFICATION = "!##$%%^";
public DownloadService() {
super("DownloadService");
}
// will be called asynchronously by Android
#Override
protected void onHandleIntent(Intent intent) {
Integer serverTrackId=intent.getIntExtra(Constants.INTENT_PARAM_SERVER_TRACK_ID, 0);
String serverUrl=intent.getStringExtra(Constants.INTENT_PARAM_SERVER_TRACK_URL);
String trackName=intent.getStringExtra(Constants.INTENT_PARAM_SERVER_TRACK_NAME);
String filePath=intent.getStringExtra(Constants.INTENT_PARAM_ROOT_FILE_PATH);
Integer localTrackId=intent.getIntExtra(Constants.INTENT_PARAM_LOCAL_TRACK_ID, 0);
File output = new File(filePath+"/"+trackName);
if (output.exists()) {
result = Activity.RESULT_OK;
publishResults(output.getAbsolutePath(), result);
}
else {
InputStream stream = null;
FileOutputStream fos = null;
try {
URL url = new URL(serverUrl);
stream = url.openConnection().getInputStream();
InputStreamReader reader = new InputStreamReader(stream);
fos = new FileOutputStream(output.getPath());
int next = -1;
while ((next = reader.read()) != -1) {
fos.write(next);
}
// successfully finished
result = Activity.RESULT_OK;
} catch (Exception e) {
e.printStackTrace();
result = Activity.RESULT_CANCELED;
} finally {
if (stream != null) {
try {
stream.close();
} catch (IOException e) {
result = Activity.RESULT_CANCELED;
e.printStackTrace();
}
}
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
result = Activity.RESULT_CANCELED;
e.printStackTrace();
}
}
}
publishResults(output.getAbsolutePath(), result);
}
}
private void publishResults(String outputPath, int result) {
try {
FileInputStream fileInputStream = new FileInputStream(outputPath);
Intent intent = new Intent(NOTIFICATION);
intent.putExtra(FILEPATH, outputPath);
intent.putExtra(RESULT, result);
sendBroadcast(intent);
}catch(Exception e){
e.printStackTrace();
}
}
}
After downloaded broadcast is made , and I try to play the mp3 file by the below code
if (trackPath != null) {
FileInputStream fileInputStream = new FileInputStream(trackPath);
mediaPlayer.setDataSource(fileInputStream.getFD());
} else {
AssetFileDescriptor afd = getResources().openRawResourceFd(R.raw.spacer_audio);
mediaPlayer.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
}
mediaPlayer.setAudioStreamType(AudioManager.STREAM_ALARM);
mediaPlayer.setLooping(false);
mediaPlayer.prepare();
mediaPlayer.setVolume(1f, 1f);
mediaPlayer.start();
I get IOException thrown from "mediaPlayer.prepare()"
I tried to play the downloaded music file through android default music player and it shows "cannot play this media".
I tried copying it to computer to try play it and I noticed there is a size difference of several KBs from the original track and the downloaded one.
Please help me find the bug.
You use InputStreamReader to read a binary file, it may produce some unexpected problems. I suggest you use BufferedInputStream instead.
BufferedInputStream reader = new BufferedInputStream(stream);
fos = new FileOutputStream(output.getPath());
int length = -1;
byte[] buffer = new byte[1024 * 8];
while ((length = reader.read(buffer)) != -1) {
fos.write(buffer, 0, length);
}

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

Android: IOException BufferedInputStream is closed after download

I've some problems with InputStream after download an image. downloadImages method return an InputStream that i write in a file. But there is an exception in inputStreamToFile method: java.io.IOException: BufferedInputStream is closed. Here the codes:
Download
public static InputStream downloadImages(String imageUrl) {
HttpURLConnection httpConn = null;
String urlBase = imageUrl;
if(D) Log.d(TAG, "downloadImages(): url request: " + urlBase);
try {
URL url = new URL(urlBase);
httpConn = (HttpURLConnection) url.openConnection();
httpConn.setConnectTimeout(SystemConstants.TIMEOUT_CONNECTION);
httpConn.setReadTimeout(SystemConstants.SOCKET_CONNECTION);
if (httpConn.getResponseCode() == HttpURLConnection.HTTP_OK) {
InputStream inputStream = httpConn.getInputStream();
return inputStream;
}
} catch (IOException e) {
Log.w(TAG, "downloadImages(): exception: " + e);
e.printStackTrace();
return null;
} catch (Exception e) {
e.printStackTrace();
} finally {
if(httpConn != null) httpConn.disconnect();
}
return null;
}
From IS to file
public static void inputStreamToFile(InputStream is) {
if(D) Log.d(TAG, "inputStreamToFile() called");
OutputStream outputStream = null;
try {
// Check if media is mounted or storage is built-in, if so, try and use external cache dir
// otherwise use internal cache dir
final String cachePath =
Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState()) ||
!Utils.isExternalStorageRemovable() ?
Utils.getExternalCacheDir(App.getContext()).getPath() :
App.getContext().getCacheDir().getPath();
// write the inputStream to a FileOutputStream
outputStream = new FileOutputStream(new File(cachePath + File.separator + "vr"));
int read = 0;
byte[] bytes = new byte[1024];
while ((read = is.read(bytes)) != -1) {
if(D) Log.d(TAG, "read called");
outputStream.write(bytes, 0, read);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (is != null) {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (outputStream != null) {
try {
if(D) Log.d(TAG, "inputStreamToFile(): outputStream is not null");
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
Put your logcat.Then only we can identify the errors,bugs,etc

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

How to store the downloaded file to sdcard and then retrieve it?

In my activity, I am downloading images from url. I want these images to be downloaded only for the first time. Later on when I visit this page, it should take the image from the sdcard. How can I do that? Can anyone help?
In manifest I have set permission:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
The method which I use for downloading is:
public static Bitmap downloadFileFromUrl(String fileUrl){
URL myFileUrl =null;
Bitmap imageBitmap = null;
try {
myFileUrl= new URL(fileUrl);
}
catch (MalformedURLException e) {
e.printStackTrace();
}
try {
HttpURLConnection connection= (HttpURLConnection)myFileUrl.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream is = connection.getInputStream();
imageBitmap = BitmapFactory.decodeStream(is);
//Below two lines I just tried out for saving to sd card.
FileOutputStream out = new FileOutputStream(fileUrl);
imageBitmap.compress(Bitmap.CompressFormat.PNG, 90, out);
}
catch (IOException e) {
e.printStackTrace();
}catch (Exception e) {
e.printStackTrace();
}
return imageBitmap;
}
Try this method
public void DownloadImage(String imageUrl)
{
InputStream is = null;
if((imageUrl == null) || (imageUrl.length() == 0) || (imageUrl == " "))
{
System.out.println("No need to download images now");
}
else
{
System.gc();
String[] items;
String ImageName = null;
URL myFileUrl =null;
Bitmap bmImg = null;
String path = IMAGE_DOWNLOAD_PATH;
FileOutputStream outStream = null;
File file = new File(path);
if(!file.exists())
{
file.mkdirs();
}
File outputFile;
BufferedOutputStream bos;
try {
myFileUrl= new URL(imageUrl.trim());
HttpURLConnection conn= (HttpURLConnection)myFileUrl.openConnection();
conn.setRequestMethod("GET");
conn.setDoInput(true);
conn.setConnectTimeout(20000);
conn.connect();
is = conn.getInputStream();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
ImageName = getImageName(imageUrl);
try {
outputFile = new File(file, ImageName);
if(outputFile.exists())
{
System.out.println("No need to download image it already exist");
outputFile.delete();
}
outputFile.createNewFile();
outStream = new FileOutputStream(outputFile);
//bos = new BufferedOutputStream(outStream);
BufferedInputStream bis = new BufferedInputStream(is);
ByteArrayBuffer baf = new ByteArrayBuffer(50);
int current = 0;
while ((current = bis.read()) != -1)
{
baf.append((byte) current);
}
outStream.write(baf.toByteArray());
outStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
and then to retrieve image from sdcard,
File extStore = Environment.getExternalStorageDirectory();
String file_path = "/(folder name)/"+"(image name)".trim()+".extension".trim();
String mypath = extStore + file_path;
Bitmap bmp=BitmapFactory.decodeFile(mypath);
ImageView image = (ImageView) v.findViewById(R.id.image);
image.setImageBitmap(bmp);
You should store somewhere what you've got in cache.
Or if your filename are unique you've to check than the file exist or not.
You have to write the data got from InputStream to specified SD card location ..

Categories

Resources