Android Webview app not downloading successful - java

My Android app has a Webview to access to my website. I noticed in the server that when a file is downloaded by the app the bandwidth used is less than when is downloaded by another device or browser.
In method onDownloadStart I call to an AsyncTask class:
protected String doInBackground(String... sUrl) {
try {
URL url = new URL(sUrl[0]);
//Getting directory to store the file
//Connection handler
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setDoOutput(true);
connection.connect();
//Obtaining filename
File outputFile = new File(directory, filename);
InputStream input = new BufferedInputStream(connection.getInputStream());
OutputStream output = new FileOutputStream(outputFile);
byte buffer[] = new byte[1024];
int bufferLength = 0;
int total = 0;
while ((bufferLength=input.read(buffer))!=-1) {
total += bufferLength;
output.write(buffer, 0, bufferLength);
}
connection.disconnect();
output.flush();
output.close();
input.close();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
Files downloaded are empty altough their filename and format are correct and I receive HTTP 200 message from the server; also execution does not enter into the while loop. I have tried to change buffer size and the problem is not solved.

Related

Video is not downloading from a URL

i want to download video from URL my function is as below
String fileURL = "http://192.168.1.2/UserFiles/Videos/OutputVideo/Birthday%20Bash5tV3fgjf4Sfi11sC.mp4";
String fileName = "Abc.mp4";
public void downloadFile(String fileURL, String fileName){
Toast.makeText(getApplicationContext(), "Download File", Toast.LENGTH_LONG).show();
try
{
URL u = new URL(fileURL);
URLConnection ucon = u.openConnection();
//Define InputStreams to read from the URLConnection.
// uses 3KB download buffer
File file =new File(Environment.getExternalStorageDirectory() + File.separator + "/Planetskool/Media/Videos/"+fileName);
InputStream is = ucon.getInputStream();
BufferedInputStream inStream = new BufferedInputStream(is, 1024 * 5);
FileOutputStream outStream = new FileOutputStream(file);
byte[] buff = new byte[5 * 1024];
//Read bytes (and store them) until there is nothing more to read(-1)
int len;
while ((len = inStream.read(buff)) != -1)
{
outStream.write(buff,0,len);
}
//clean up
outStream.flush();
outStream.close();
inStream.close();
}
catch (Exception se)
{
se.printStackTrace();
}
}
its downloading video in 0kb whats wrong with this
use async method to download file from URL.
Three things might be happened
Missing Internet permission
Missing Write external storage permission
"/Planetskool/Media/Videos/" Directory not exist, Create dir first.
http://192.168.1.2 it is not internet URL check your URL

The Quality of The Audio Downloaded from Web Service is not Good Enough

I am developing an Android Application and the below method successfully downloads an audio/sound file from web service. But the sound quality is not good enough.I test it both with emulator and a real device and also I play the downloaded file on Mac Media Player by the help of Eclipse File Explorer and I see the problem exists in all and so I think that the downloaded audio file has some problems. I also developed its iOS App and there is no problem there which means the web service works correctly.Any help will be very much appreciated. Method parameters is as below
URL = https://xx.xxx.net/xfolder/webservice_method_name.php/
query = parameter1=somevalue1&_parameter2=somevalue2
public static String downloadFile(String URL, String query) {
String result = "";
try {
URL myurl = new URL(URL);
HttpsURLConnection con = (HttpsURLConnection) myurl.openConnection();
con.setRequestMethod("POST");
con.setRequestProperty("Content-length", String.valueOf(query.length()));
con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
con.setDoOutput(true);
con.setDoInput(true);
DataOutputStream output = new DataOutputStream(con.getOutputStream());
output.writeBytes(query);
output.close();
MyManager sharedManager = MyManager.getInstance();
FileOutputStream f = new FileOutputStream(new File(sharedManager.appDirectory, ApplicationConstants.SOUND_FILE_NAME));
InputStream in = con.getInputStream();
byte[] buffer = new byte[output.size()];
int len1 = 0;
while ((len1 = in.read(buffer)) > 0) {
f.write(buffer);
}
f.close();
result = "success";
} catch (Exception e) {
Log.i("exception: ", e.getMessage());
result = "failed";
}
return result;
}
I have solved the problem. It is not related with the downloadFile method/service. I set the android media player audio stream type as stream music.

Android: Get a file from http and store in SDCard

I've followed what is written in many similar questions but there is still a problem
From a jsp I get a pdf, if i go to the URL the browser opens automatically the pdf, jsp page does something like:
//Gets the pdf from the database
BufferedInputStream bis = new BufferedInputStream(file.getBinaryStream(), buffer);
ByteArrayOutputStream baos=new ByteArrayOutputStream();
int readed=0;
while ((readed=bis.read())!=-1) baos.write(readed);
bis.close();
byte[] pdf=baos.toByteArray();
response.setContentType("application/pdf");
response.setContentLength(pdf.length);
response.getOutputStream().write(pdf, 0, pdf.length);
This code works because if we browse to the URL we get the PDF into the browser.
Then in Android I do in an AsyncTask:
InputStream is = null;
try {
URL url = new URL(myurl); // <-- this is the same URL tested into browser
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setDoOutput(true);
urlConnection.connect();
FileOutputStream fos = new FileOutputStream(getWorkingDir()+fileName);
InputStream inputStream = urlConnection.getInputStream();
int totalSize = urlConnection.getContentLength(); //<- this seems to be incorrect, totalSize value is 22 but file is more than 50Kb length
int downloadedSize = 0;
byte[] buffer = new byte[1024];
int bufferLength = 0; //used to store a temporary size of the buffer
while ( (bufferLength = inputStream.read(buffer)) >=0) {
fos.write(buffer, 0, bufferLength);
downloadedSize += bufferLength;
// at this point downloadedSize is only 2, and next iteration in while exists so a file os size 2bytes is created...
}
fos.close();
Of course I've the permission to write in SD and use Internet in the AndrodiManifest.xml
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
I've tried directly with URLConnection, getting the InputStream and we get the same, only reading 2 bytes...
Write to external file is working, if I try to write a string.getBytes() to a file it's written.
If we get conn.getResponseCode() it's 200, so it's ok.
The same .jsp can according to parameters return a list of documents (in JSON) or a PDF if we provide his database ID, if we get the list of pdf, it works, in this case it's readed like:
reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
stringBuilder = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
stringBuilder.append(line);
}
Any idea why is not working when it tries to get the binary pdf file?
Where is the failure?
Thanks for your expertice...
Its working for me Try to modify this :
private void savePrivateExternalFile(String fileURL, String fName) {
HttpURLConnection connection = null;
URL url = null;
try {
url = new URL(fileURL);
connection = (HttpURLConnection) url.openConnection();
connection.addRequestProperty(BConstant.WEB_SERVICES_COOKIES,
cookie);
connection.setDoOutput(true);
connection.connect();
} catch (IOException e1) {
e1.printStackTrace();
}
File folderDir = null;
folderDir = new File(getExternalFilesDir("Directory Name") + "/Files");
File file = new File(folderDir, fName);
if (file.exists()) {
file.delete();
}
if ((folderDir.mkdirs() || folderDir.isDirectory())) {
try {
InputStream inputStream = connection.getInputStream();
BufferedInputStream bufferedInputStream = null;
bufferedInputStream = new BufferedInputStream(inputStream,
1024 * 5);
FileOutputStream fileOutputStream = new FileOutputStream(
folderDir + "/" + fName);
byte[] buffer = new byte[1024];
int len1 = 0;
while ((len1 = inputStream.read(buffer)) != -1) {
fileOutputStream.write(buffer, 0, len1);
}
bufferedInputStream.close();
fileOutputStream.close();
inputStream.close();
connection.disconnect();
} catch (Exception e) {
e.printStackTrace();
}
}
Use this if you want to open Downloaded file :
File file = new File(getExternalFilesDir("Directory Name")+ "/Files/" + fileName);
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(file),"application/pdf");
intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
startActivity(intent);
Add this line in your Manifest file:
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

Android Partially Downloaded Files Report Wrong File Size

I'm putting together some code to download files from an HTTP address in Android. I'd like to support download resumption if the download fails mid way.
The output I get when starting the download, then killing the wifi connection and restarting again several times is the following:
Start size 0
Stop size 12333416
Start size 12333416
Stop size 16058200
Start size 3724784
I cannot understand why after the first resumption, subsequent file size readings of the partially downloaded file do not match.
Thanks in advance!
public void download(String source, String target) throws IOException {
BufferedOutputStream outputStream = null;
InputStream inputStream = null;
try {
File targetFile = new File(target);
currentBytes = targetFile.length();
Log.i(TAG, "Start size " + String.valueOf(currentBytes));
outputStream = new BufferedOutputStream(new FileOutputStream(targetFile));
// create the input stream
URLConnection connection = (new URL(source)).openConnection();
connection.setConnectTimeout(mCoTimeout);
connection.setReadTimeout(mSoTimeout);
inputStream = connection.getInputStream();
inputStream.skip(currentBytes);
// calculate the total bytes
totalBytes = connection.getContentLength();
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) > 0) {
// write the bytes to file
outputStream.write(buffer, 0, bytesRead);
outputStream.flush();
currentBytes += bytesRead;
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (outputStream != null) {
// close the output stream
outputStream.flush();
outputStream.close();
}
if (inputStream != null) {
// close the input stream
inputStream.close();
}
Log.i(TAG, "Stop size " + String.valueOf(currentBytes));
}
}
There are two things you are doing wrong:
To resume download to file you should append, not rewrite the file. Use special constructor for output stream:
FileOutputStream(targetFile, true)
To request part of file from server you should use HTTP 1.1 property "Range". You can do it like this:
HttpURLConnection httpConnection = (HttpURLConnection) connection;
connection.setRequestProperty("Range", "bytes=" + currentBytes + "-");

Java uploading .png to server using php POST data

This is the method I have in my java application. It is reading the bytes correctly, I have logged to see if it was. The problem is that the php is not realizing the data is there. I have tested and the .php reads that $_POST is set, but is empty.
public void screenshot(BufferedImage screenshot) {
try {
ImageIO.write(screenshot, "png",
new File(Environment.getStorageDirectory().toString()
.concat(File.separator + SCRIPT_NAME + ".png")));
HttpURLConnection httpUrlConnection;
OutputStream outputStream;
BufferedInputStream fileInputStream;
BufferedReader serverReader;
int totalBytes;
String response = "";
String serverResponse = "";
String localFileName = Environment.getStorageDirectory().toString()
.concat(File.separator + SCRIPT_NAME + ".png");
// Establish a connection
httpUrlConnection = (HttpURLConnection) new URL(
"http://www.scripted.it/scriptoptions/utils/saveScreenshot.php?user="
+ SupraCrafter.statHandler.getUser())
.openConnection();
httpUrlConnection.setDoOutput(true);
httpUrlConnection.setDoInput(true);
httpUrlConnection.setRequestMethod("POST");
httpUrlConnection.setRequestProperty("Content-type",
"application/x-www-form-urlencoded");
outputStream = httpUrlConnection.getOutputStream();
// Buffered input stream
fileInputStream = new BufferedInputStream(new FileInputStream(
localFileName));
// Get the size of the image
totalBytes = fileInputStream.available();
// Loop through the files data
for (int i = 0; i < totalBytes; i++) {
// Write the data to the output stream
outputStream.write(fileInputStream.read());
}
// Close the output stream
outputStream.close();
// New reader to get server response
serverReader = new BufferedReader(new InputStreamReader(
httpUrlConnection.getInputStream()));
// Read the servers response
serverResponse = "";
while ((response = serverReader.readLine()) != null) {
serverResponse = serverResponse + response;
}
System.out.println(serverResponse);
// Close the buffered reader
serverReader.close();
} catch (Exception e) {
e.printStackTrace();
}
try {
URL url = new URL(
"http://scripted.it/scriptoptions/utils/setScreenshotStatus.php?user="
+ SupraCrafter.statHandler.getUser() + "&pass="
+ SupraCrafter.statHandler.getPass() + "&script="
+ SCRIPT_NAME + "&status=1");
BufferedReader in = new BufferedReader(new InputStreamReader(
url.openStream()));
in.close();
} catch (MalformedURLException e) {
} catch (IOException e) {
}
}
Here is the .php file:
<?
// Config
$uploadBase = "../screenshots/";
$uploadFilename = $_GET['user'] . ".png";
$uploadPath = $uploadBase . $uploadFilename;
// Upload directory
if(!is_dir($uploadBase))
mkdir($uploadBase);
// Grab the data
$incomingData = file_get_contents('php://input');
// Valid data?
if(!$incomingData)
die("No input data");
// Write to disk
$fh = fopen($uploadPath, 'w') or die("Error opening file");
fwrite($fh, $incomingData) or die("Error writing to file");
fclose($fh) or die("Error closing file");
echo "Success";
?>
It always echos 'no input data.'
You are not encoding the content with application/x-www-form-urlencoded. You should not simply copy the bytes into the HTTP payload, but instead encode it correctly.
application/x-www-form-urlencoded is not the only possible way of encoding it, multipart/form-data is another common choice. Both are supported by almost all webservers, and as a consequence by PHP.
A tutorial on how to encode using Java is here : http://www.devx.com/Java/Article/17679
Why don't you use Apache's HttpClient or similar library that already do that tedious work for you?
Apache HttpClient : http://hc.apache.org/httpcomponents-client-ga/

Categories