I'm developping in galaxy note 10.1
the download action start java spring action.
this download action is well proceed in PC, browser in mobile device
the problem is galaxy note 10.1 built-in browser
this browser's userAgent is
"Mozilla/5.0 (Linux; U; Android 4.0.4; ko-kr; SHW-M480W Build/IMM76D) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Safari/534.30"
and android's download method is
mWebView.setDownloadListener(new DownloadListener(){
public void onDownloadStart(String url, String sUserAgent, String contentDisposition, String mimetype, long contentLength) {
URL urls = null;
String fileUrl = "";
String mPath = "";
Log.v("sUserAgent", sUserAgent);
String condition[] = contentDisposition.split("=");
String x = condition[1];
Log.d("test",x);
try {
fileUrl = URLDecoder.decode(x, "UTF-8");
} catch(Exception e) {
e.printStackTrace();
}
try {
urls = new URL(url);
} catch (MalformedURLException e) {
e.printStackTrace();
}
String fileName[] = url.split("/");
Log.d("test", url);
try {
HttpURLConnection conn= (HttpURLConnection)urls.openConnection();
conn.setDoOutput(true);
conn.connect();
mPath = Environment.getExternalStorageDirectory()+"/Download/";
String chkPath = Environment.getExternalStorageDirectory()+"/Download/"+fileUrl;
File chkFile = new File(chkPath);
if(chkFile.exists() == true){}
else {
File f = new File(mPath);
f.mkdirs();
File OutputFile = new File(f, fileUrl);
FileOutputStream fos = new FileOutputStream(OutputFile);
InputStream is = conn.getInputStream();
byte[]buffer = new byte[24576];
int len1 = 0;
while((len1 = is.read(buffer)) != -1) {
fos.write(buffer, 0, len1);
}
fos.close();
is.close();
}
} catch (IOException e) {
e.printStackTrace();
}
Toast.makeText(getApplicationContext(), "DOWNLOAD COMPLETED", 0).show();
File files = new File(mPath+fileUrl);
Log.e("msg",mPath+fileUrl+"");
Intent intent = new Intent(Intent.ACTION_VIEW);
String mimes = fileUrl.substring(fileUrl.length()-3, fileUrl.length());
if(mimes.equals("hwp")) {
intent.setDataAndType(Uri.fromFile(files), "application/x-hwp");
} else {
intent.setDataAndType(Uri.fromFile(files), "application/"+mimes);
}
startActivity(intent);
}
});
the spring download action is
String mimetype = "application/x-msdownload";
response.setContentType(mimetype);
response.setHeader("fileName", fvo.getFileStreCours()+fvo.getStreFileNm());
setDisposition(fvo.getOrignlFileNm(), request, response);
response.setContentLength(fSize);
BufferedInputStream in = null;
BufferedOutputStream out = null;
try {
in = new BufferedInputStream(new FileInputStream(uFile));
out = new BufferedOutputStream(response.getOutputStream());
FileCopyUtils.copy(in, out);
out.flush();
response.flushBuffer();
} catch (Exception ex) {
// Connection reset by peer: socket write error
log.debug("IGNORED: " + ex.getMessage());
} finally {
if (in != null) {
try {
in.close();
} catch (Exception ignore) {
log.debug("IGNORED: " + ignore.getMessage());
}
}
if (out != null) {
try {
out.close();
} catch (Exception ignore) {
log.debug("IGNORED: " + ignore.getMessage());
}
}
}
this file is downloading from NAS
but android was not access web's response buffer
in android, maked 0 byte file.
how to access buffer and download file in web's response buffer?
ps. web service not allow open url, so I can't use redirect
Related
I am developing app like playstore in which user can download any app. i have many apps in my application that i got from my website through wp api v2. when we click on any of the available application detail opened and it have a download link. when we click on the link it goes to the browser but what i want is when we click on any of the apps downloading link downloading should start within my app with progress bar. i didn't found any appropriate solution yet on stack or anywhere.
Here is the screenshot attached for better understanding. arrow is pointing to the downloading link.
Try this code, you can put this on click of the link(textview)
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
}
}
you can use intent service to download the app.
Here is the code :
public class DownloadService extends IntentService {
File cacheDir;
public DownloadService() {
super("DownloadService");
}
#Override
public void onCreate() {
super.onCreate();
String tmpLocation =
Environment.getExternalStorageDirectory().getPath();
cacheDir = new File(tmpLocation);
if (!cacheDir.exists()) {
cacheDir.mkdirs();
}
}
#Override
protected void onHandleIntent(Intent intent) {
String remoteUrl = intent.getExtras().getString("url");
String location;
String filename =
remoteUrl.substring(
remoteUrl.lastIndexOf(File.separator) + 1);
File tmp = new File(cacheDir.getPath()
+ File.separator + filename);
if (tmp.exists()) {
location = tmp.getAbsolutePath();
stopSelf();
return;
}
try {
URL url = new URL(remoteUrl);
HttpURLConnection httpCon =
(HttpURLConnection) url.openConnection();
if (httpCon.getResponseCode() != 200)
throw new Exception("Failed to connect");
InputStream is = httpCon.getInputStream();
ByteArrayOutputStream out = new ByteArrayOutputStream();
byte[] buf = new byte[1024];
int n = 0;
while (-1 != (n = is.read(buf))) {
out.write(buf, 0, n);
}
out.close();
is.close();
byte[] response = out.toByteArray();
FileOutputStream fos = new FileOutputStream(tmp);
fos.write(response);
fos.flush();
fos.close();
is.close();
location = tmp.getAbsolutePath();
} catch (Exception e) {
Log.e("Service", "Failed!", e);
}
}
}
Run this service with url passed in the intent
I am learning Android and porting my Windows app to Android platform. I need an advice how to download a small text file and read content of this file.
I have following code in my Windows app, I need to rewrite it for Android app:
string contents = "file.txt";
string neturl = "http://www.example.com/file.txt";
HttpClient client = new HttpClient();
try {
HttpResponseMessage message = await client.GetAsync(neturl);
StorageFolder folderForFile = Windows.Storage.ApplicationData.Current.LocalFolder;
StorageFile fileWithContent = await folderForFile.CreateFileAsync(channels, CreationCollisionOption.ReplaceExisting);
byte[] bytesToWrite = await message.Content.ReadAsByteArrayAsync();
await FileIO.WriteBytesAsync(fileWithContent, bytesToWrite);
var file = await folderForFile.GetFileAsync(contents);
var text = await FileIO.ReadLinesAsync(file);
foreach (var textItem in text)
{
string[] words = textItem.Split(',');
...
I have found what on Android I need to create following class for async download
public class DownloadFileFromURL extends AsyncTask<String, String, String> {
/**
* Downloading file in background thread
* */
#Override
protected String doInBackground(String... f_url) {
int count;
try {
URL url = new URL(f_url[0]);
URLConnection conection = url.openConnection();
conection.connect();
// download the file
InputStream input = new BufferedInputStream(url.openStream(), 8192);
// Output stream
OutputStream output = new FileOutputStream("file.txt");
byte data[] = new byte[1024];
while ((count = input.read(data)) != -1) {
// writing data to file
output.write(data, 0, count);
}
// flushing output
output.flush();
// closing streams
output.close();
input.close();
} catch (Exception e) {
Log.e("Error: ", e.getMessage());
}
return null;
}
In the code above I try to download file and name it as "file.txt", but get exception 'FileNotFoundException file.txt open failed: EROFS (Read-only file system)", I need to save it internally (I do not want to let users to see this file in the file explorers) and rewrite file if it exists.
And I try to execute this task and read file
void DownloadAndReadContent() {
new DownloadFileFromURL().execute("http://www.example.com/file.txt");
try {
BufferedReader br = new BufferedReader(new InputStreamReader(openFileInput("file.txt")));
String str = "";
while ((str = br.readLine()) != null) {
Log.d(LOG_TAG, str);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
so downloading to SD card is working
protected String doInBackground(String... f_url) {
int count;
try {
URL url = new URL(f_url[0]);
URLConnection conection = url.openConnection();
conection.connect();
InputStream input = new BufferedInputStream(url.openStream(), 8192);
File SDCardRoot = Environment.getExternalStorageDirectory();
SDCardRoot = new File(SDCardRoot.getAbsolutePath() + "/plus");
SDCardRoot.mkdir();
File file = new File(SDCardRoot,"settings.dat");
FileOutputStream output = new FileOutputStream(file);
byte data[] = new byte[1024];
while ((count = input.read(data)) != -1) {
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
} catch (Exception e) {
Log.e("Error: ", e.getMessage());
}
return null;
}
and reading:
new DownloadFileFromURL().execute("http://www.example.com/file.txt");
if (!Environment.getExternalStorageState().equals(
Environment.MEDIA_MOUNTED)) {
Log.d(LOG_TAG, "SD n\a " + Environment.getExternalStorageState());
return;
}
File sdPath = Environment.getExternalStorageDirectory();
sdPath = new File(sdPath.getAbsolutePath() + "/plus");
File sdFile = new File(sdPath, "settings.dat");
try {
BufferedReader br = new BufferedReader(new FileReader(sdFile));
String str = "";
while ((str = br.readLine()) != null) {
String[] words = str.split(",");
// do some work
}
}
Log.d(LOG_TAG, str);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
In my WebView am trying to download some files from some web sites but on execution of http response it is giving an error saying "Target host must not be null,".
My piece of code is...
// TODO: Download Listener
webview.setDownloadListener(new DownloadListener() {
#Override
public void onDownloadStart(String url, String sUserAgent,
String contentDisposition, String mimetype,
long contentLength) {
if (sUserAgent == null) {
Log.e(TAG + " - Conexion", "Error on useragent");
}
String PATH = Environment.getExternalStorageDirectory()
+ "/download/";
Log.v("", "PATH: " + PATH);
File file = new File(PATH);
if (file.mkdirs()) {
System.out.println("Directry-->" + PATH + " is created");
}
try {
mUrl = new URL(url);
} catch (MalformedURLException e2) {
e2.printStackTrace();
}
String fileName = getFileName(mUrl);
File outputFile = new File(file, fileName);
try {
fos = new FileOutputStream(outputFile);
} catch (FileNotFoundException e1) {
e1.printStackTrace();
}
client = new DefaultHttpClient();
try {
HttpPost request = new HttpPost(URLEncoder.encode(url, "UTF-8"));
} catch (UnsupportedEncodingException e1) {
e1.printStackTrace();
}
request.setHeader("User-Agent", sUserAgent);
try {
response = client.execute(request);
StatusLine status = response.getStatusLine();
if (status.getStatusCode() != HTTP_STATUS_OK) {
Toast.makeText(myApp, "Error On Download",Toast.LENGTH_SHORT).show();
} else {
InputStream in = response.getEntity().getContent();
byte[] read = new byte[1024];
int numReadBytes = 0, singleByte;
boolean endFlow = false;
do {
singleByte = in.read();
endFlow = singleByte == -1;
if (!endFlow) {
read[numReadBytes] = (byte) singleByte;
numReadBytes++;
}
} while (!endFlow);
if (numReadBytes > 0) {
fos.write(read, 0, numReadBytes);
}
}
} catch (IOException e) {
Log.e(TAG + " - Conexion", e.getMessage());
} catch (ArrayIndexOutOfBoundsException e) {
Log.e(TAG + " - Conexion", e.getMessage());
}
}
});
Try to use:
Add "http://" to "api.i-v-o.ch"
So it should be: "http://api.i-v-o.ch"
mostly it will help you...
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.
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();