I am trying to cache of videos by this
try {
URL oracle = new URL(url);
URLConnection yc = oracle.openConnection();
InputStream in = yc.getInputStream();
File file = new File(getApplicationContext().getCacheDir() ,url);
if(!file.exists()){
file.setReadable(true);
file.createNewFile();
if (file.canWrite()){
FileOutputStream out = new FileOutputStream(file);
byte[] buffer = new byte[1024];
int len1 = 0;
while ( (len1 = in.read(buffer)) > 0 ) {
out.write(buffer,0, len1);
}
out.close();
}
in.close();
Runtime.getRuntime().exec("chmod 755 "+getCacheDir() +"/"+ url);
videoView.setVideoPath("chmod 755 "+getCacheDir() +"/"+ url);
}else {
videoView.setVideoURI(Uri.parse(videoUrl));
}
} catch (Exception e) {
// TODO: handle exception
}
videoView.setVideoURI(Uri.parse(videoUrl));
MediaController mc = new MediaController(VideoViewC.this);
videoView.setMediaController(mc);
videoView.requestFocus();
videoView.start();
mc.show();
But I found Error java.net.SocketException: Connection reset by peer.
if you have any suggestion please give me.
I have my case problem, and it consisted in particular the my http server, which if not properly authenticate just closed the client connection, it is my Ask:
android-async-http Status code and response to onFailure
Maybe you have it too, due to the peculiarities of your httpservers
Did you implement caching video files?
Related
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
I have a code to download a video from my server and save it in the sd card. I use this code:
String videoURL = "http://www.myapp.com" + key + "/"+key+".avi";
String PATHSdcard = getSDFile();
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(videoURL);
//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(PATHSdcard,key+".avi");
//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();
//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.flush();
fileOutput.close();
sendBroadcast (
new Intent(Intent.ACTION_MEDIA_MOUNTED,
Uri.parse("file://" + Environment.getExternalStorageDirectory()))
);
//catch some possible errors...
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
I download it correctly, but I can't play the video after downloaded it.
If I close my application and open again, the video works fine. Any solution?
Thanks in advance
Ensure you have the correct permissions to write to the file. In your manifest file, include this line
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />.
UPDATED:
I am not sure what problem in your code, but can you try my code, maybe it will work:
public void DownloadFromUrl(String DownloadUrl, String fileName) {
try {
File root = android.os.Environment.getExternalStorageDirectory();
File dir = new File (root.getAbsolutePath() + "/your_downloads");
if(dir.exists()==false) {
dir.mkdirs();
}
URL url = new URL(DownloadUrl); //you can write here any link
File file = new File(dir, fileName);
/* Open a connection to that URL. */
URLConnection ucon = url.openConnection();
/*
* Define InputStreams to read from the URLConnection.
*/
InputStream is = ucon.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
/*
* Read bytes to the Buffer until there is nothing more to read(-1).
*/
ByteArrayBuffer baf = new ByteArrayBuffer(5000);
int current = 0;
while ((current = bis.read()) != -1) {
baf.append((byte) current);
}
/* Convert the Bytes read to a String. */
FileOutputStream fos = new FileOutputStream(file);
fos.write(baf.toByteArray());
fos.flush();
fos.close();
} catch (IOException e) {
Log.d("DownloadManager", "Error: " + e);
}
}
Im downloading files from a server, some big, some small.
protected Long doInBackground(Object... params) {
Context context = (Context) params[0];
String name = (String) params[1];
String urlString = (String) params[2];
File mediadir = context.getDir("tvr", Context.MODE_PRIVATE);
try {
URL url = new URL(urlString);
URLConnection connection = url.openConnection();
connection.connect();
int lenghtOfFile = connection.getContentLength();
InputStream is = url.openStream();
Log.d("DOWNLOAD NAME",name);
File new_file = new File(mediadir, name);
FileOutputStream fos = new FileOutputStream(new_file.getPath());
byte data[] = new byte[1024];
int count = 0;
long total = 0;
int progress = 0;
while ((count=is.read(data)) != -1){
total += count;
int progress_temp = (int)total*100/lenghtOfFile;
if(progress_temp%10 == 0 && progress != progress_temp){
progress = progress_temp;
}
fos.write(data, 0, count);
}
is.close();
fos.close();
} catch (Exception e) {
// TODO Auto-generated catch block
Log.e("DOWNLOAD ERROR", e.toString());
}
return null;
}
As I now understand it, Im downloading the file via a stream and streaming the data into a file. So in effect the file is created since the first byte of data.
Now, on the other end of things Im playing files from my internal directory by looking for files in a directory and then playing them:
mediaPlayer = new MediaPlayer();
mediaPlayer.setOnCompletionListener(this);
mediaPlayer.setDisplay(holder);
FileInputStream fileInputStream = new FileInputStream(path);
mediaPlayer.setDataSource(fileInputStream.getFD());
fileInputStream.close();
mediaPlayer.prepare();
mediaPlayer.start();
Now this issue is that the file will be played even though its not fully downloaded!
Is this true? If so, how must I check if the file is complete before trying to play it?
Yes, this is a valid scenario, as in many cases your download speed will be slower than the reading and playing speed of the MediaPlayer.
Seeing as you're using an AsyncTask, you can fix this problem by calling the playing code in the onPostExecute() method, as that only runs after all work in the doInBackground() method has completed.
private void doFileDownload() throws Exception {
BufferedInputStream in = null;
BufferedOutputStream out = null;
String url = "http://www.jimsonmok.com/server/uploads/"; //input
String file = "/sdcard/Shek Kip Mei MTR Station Exit A.3gp"; //output
try{
url += URLEncoder.encode("Shek Kip Mei MTR Station Exit A.3gp");
URL download = new URL(url);
URLConnection downloadConnection = download.openConnection(); //set up connection
in = new BufferedInputStream(downloadConnection.getInputStream());
out = new BufferedOutputStream(new FileOutputStream(file));
int contentlength = downloadConnection.getContentLength(); //getting the length of the file
for(int counter=0;counter < contentlength;counter++) //storing the binary I/O file
out.write(in.read());
}catch(IOException e){
}
in.close();
out.close();
}
I am trying to download an audio from the server using an android phone.
The code above I am using does not work in android.
Does anyone know the reasons?
Thanks a lot!
how can i download audio file from server by url and save it to sdcard.
i am using the code below:
public void uploadPithyFromServer(String imageURL, String fileName) {
try {
URL url = new URL(GlobalConfig.AppUrl + imageURL);
File file = new File(fileName);
Log.d("ImageManager", "download begining");
Log.d("ImageManager", "download url:" + url);
Log.d("ImageManager", "downloaded file name:" + fileName);
/* Open a connection to that URL. */
URLConnection con = url.openConnection();
InputStream is = con.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is, 1024 * 50);
FileOutputStream fos = new FileOutputStream("/sdcard/" + file);
byte[] buffer = new byte[1024 * 50];
int current = 0;
while ((current = bis.read(buffer)) != -1) {
fos.write(buffer, 0, current);
}
fos.flush();
fos.close();
bis.close();
} catch (IOException e) {
Log.d("ImageManager", "Error: " + e);
}
}
the above code is not downloading audio file.
if use any permission in menifest file plz tell me.. (i have used internet permission)
please help
thanks..
you must also add
android.permission.WRITE_EXTERNAL_STORAGE
permission if you wish to write data to sd card.
also post your logcat output , if you are getting any IOExceptions.
Your example does not specify a request method and some mimetypes and stuff.
Here you will find a list of mimetypes http://www.webmaster-toolkit.com/mime-types.shtml
Find the mimetypes relevant to you and add it to the mimetypes specified below in the code.
Oh and btw, the below is normal Java code. You'll have to replace the bit that stores the file on the sdcard. dont have an emulator or phone to test that part at the moment
Also see the docs for storage permissions on sd here: http://developer.android.com/reference/android/Manifest.permission_group.html#STORAGE
public static void downloadFile(String hostUrl, String filename)
{
try {
File file = new File(filename);
URL server = new URL(hostUrl + file.getName());
HttpURLConnection connection = (HttpURLConnection)server.openConnection();
connection.setRequestMethod("GET");
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setUseCaches(false);
connection.addRequestProperty("Accept","image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/msword, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/x-shockwave-flash, */*");
connection.addRequestProperty("Accept-Language", "en-us,zh-cn;q=0.5");
connection.addRequestProperty("Accept-Encoding", "gzip, deflate");
connection.connect();
InputStream is = connection.getInputStream();
OutputStream os = new FileOutputStream("c:/temp/" + file.getName());
byte[] buffer = new byte[1024];
int byteReaded = is.read(buffer);
while(byteReaded != -1)
{
os.write(buffer,0,byteReaded);
byteReaded = is.read(buffer);
}
os.close();
} catch (IOException e) {
e.printStackTrace();
}
Then call,
downloadFile("http://localhost/images/bullets/", "bullet_green.gif" );
EDIT:
Bad coder me.
Wrap that input InputStream in a BufferedInputStream. No need to specify buffersizes ect.
Defaults are good.