I want to download this pdf file
https://scholar.najah.edu/sites/default/files/book/dllt-lhwy-wlrmz-fy-lfwlklwr-lshby.pdf
I am using this code to download pdf files, it works fine with many files but it failed on pdf file like above
public void downloadFile(#NonNull String urlStr, #NonNull String fullFilePath,
#NonNull DownloadListener downloadListener) {
cancelStatus = false;
InputStream is = null;
File ffPath = null;
FileOutputStream fos = null;
try {
downloadListener.onProgress(0);
URL url = new URL(urlStr);
URLConnection conexion = url.openConnection();
conexion.setReadTimeout(2000000);
conexion.setRequestProperty("User-Agent", "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_5_8; en-US) AppleWebKit/532.5 (KHTML, like Gecko) Chrome/4.0.249.0 Safari/532.5");
System.setProperty("http.agent", "");
conexion.connect();
int lenghtOfFile = conexion.getContentLength();
if (lenghtOfFile <= 0) lenghtOfFile = 1;
is = url.openStream();
ffPath = new File(fullFilePath);
fos = new FileOutputStream(ffPath);
int count = 0;
long total = 0;
int progress = 0;
byte data[] = new byte[1024];
while ((count = is.read(data)) != -1) {
if (cancelStatus == true) {
break;
}
total += count;
int progress_temp = (int) total * 100 / lenghtOfFile;
if (progress != progress_temp) {
progress = progress_temp;
downloadListener.onProgress(progress >= 0 && progress <= 100 ? progress : 0);
}
fos.write(data, 0, count);
cancelStatus = downloadListener.onPacketDownloaded(total, lenghtOfFile);
}
if (is != null) is.close();
if (fos != null) fos.close();
if (lenghtOfFile <= 1) {
downloadListener.onComplete();
} else if (ffPath.length() < lenghtOfFile) {
if (cancelStatus) {
downloadListener.onCancel();
} else {
downloadListener.onError();
}
} else if (ffPath.length() >= lenghtOfFile) {
downloadListener.onComplete();
}
if (cancelStatus == true) {
if (ffPath != null) ffPath.delete();
}
} catch (MalformedURLException e) {
try {
if (is != null) is.close();
if (fos != null) fos.close();
} catch (IOException e1) {
e1.printStackTrace();
}
if (ffPath != null) ffPath.delete();
downloadListener.onError();
// TODO Auto-generated catch block
e.printStackTrace();
} catch (FileNotFoundException e) {
try {
if (is != null) is.close();
if (fos != null) fos.close();
} catch (IOException e1) {
e1.printStackTrace();
}
if (ffPath != null) ffPath.delete();
downloadListener.onError();
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
try {
if (is != null) is.close();
if (fos != null) fos.close();
} catch (IOException e1) {
e1.printStackTrace();
}
if (ffPath != null) ffPath.delete();
downloadListener.onError();
// TODO Auto-generated catch block
e.printStackTrace();
}
}
the problem is count = is.read(data) return -1 and break from while loop after one loop, the file about 345 kb
please help
/**
* download file used too download the file and save into phone
*
* #param fileURL contain file url
* #param fileName contain file name
*/
public void DownloadFile(String fileURL, String fileName) {
try {
String RootDir = Environment.getExternalStorageDirectory()
+ File.separator + "Cards List";
File RootFile = new File(RootDir);
RootFile.mkdir();
// File root = Environment.getExternalStorageDirectory();
java.net.URL u = new URL(fileURL);
HttpURLConnection c = (HttpURLConnection) u.openConnection();
c.setRequestMethod("GET");
c.setDoOutput(true);
c.connect();
FileOutputStream f = new FileOutputStream(new File(RootFile,
fileName + " abc " + ".pdf"));
InputStream in = c.getInputStream();
byte[] buffer = new byte[1024];
int len1 = 0;
while ((len1 = in.read(buffer)) > 0) {
f.write(buffer, 0, len1);
}
f.close();
} catch (Exception e) {
Log.d("Error....", e.toString());
}
} // used to download the file from server
class ProgressBack extends AsyncTask<String, Void, Void> {
ProgressDialog PD;
#Override
protected void onPreExecute() {
super.onPreExecute();
PD = ProgressDialog.show(MainActivity.this, null, "Please Wait ...", true);
PD.setCancelable(true);
}
#Override
protected Void doInBackground(String... params) {
DownloadFile("https://scholar.najah.edu/sites/default/files/book/dllt-lhwy-wlrmz-fy-lfwlklwr-lshby.pdf",
"Cards List"); // calling DownloadFile
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
PD.dismiss();
Toast.makeText(MainActivity.this, "Download Completed", Toast.LENGTH_SHORT).show();
}
}
Related
I'm having a hard time with calling a function when I select on the files.
When I select on a file, it start to take like 10 seconds before it start to call the UploadFile function and then connect to the server, so when I select more files to add, it will take like a minute or so before it start to call the UploadFile function and connect to the server which is wrong. It should have start to call the UploadFile function instantly and connect to the server when I am adding more than one files.
Below is the full code:
public class ComposeActivity extends AppCompatActivity implements AdapterView.OnItemSelectedListener {
private static final int CHOOSE_FILE_REQUESTCODE = 1;
private RecyclerView mFilesDetailRecyclerView;
private ArrayList<String> mSelectedFilesList = new ArrayList<>();
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK && requestCode == CHOOSE_FILE_REQUESTCODE) {
try {
Uri uri = data.getData();
Cursor cursor = getContentResolver().query(uri, null, null, null, null);
int index = cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME);
Context context = getApplicationContext();
FilePath = RealPathUtil.getRealPath(context, uri);
cursor.moveToFirst();
//mSelectedFilesList.add(cursor.getString(index));
mSelectedFilesList.add(FilePath);
mAdapter.notifyItemInserted(mSelectedFilesList.size());
Log.e("message.......", "caught this.....");
upload_File = new File(FilePath);
FileName = upload_File.getName();
new UploadFile().execute();
} catch (Exception e) {
Toast.makeText(ComposeActivity.this, "Choose any other file", Toast.LENGTH_SHORT).show();
}
}
}
#SuppressLint("StaticFieldLeak")
private class UploadFile extends AsyncTask<Void, Void, Void> {
#RequiresApi(api = Build.VERSION_CODES.O)
#Override
protected Void doInBackground(Void... params) {
HttpURLConnection urlConnection = null;
try {
String twoHyphens = "--";
String boundary = "*****" + System.currentTimeMillis() + "*****";
String lineEnd = "\r\n";
Log.e("message.......", "FileName...." + FileName);
URL url = new URL("https://www.example.com/fileupload1.php");
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setUseCaches(false);
urlConnection.setDoOutput(true);
urlConnection.setDoInput(true);
urlConnection.setRequestMethod("POST");
urlConnection.setConnectTimeout(200);
urlConnection.setReadTimeout(200);
urlConnection.setRequestProperty("Connection", "Keep-Alive");
urlConnection.setRequestProperty("ENCTYPE", "multipart/form-data");
urlConnection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
urlConnection.setRequestProperty("uploaded_file", FileName);
FileInputStream fileInputStream = new FileInputStream(upload_File);
DataOutputStream dataOutputStream = new DataOutputStream(urlConnection.getOutputStream());
dataOutputStream.writeBytes(twoHyphens + boundary + lineEnd);
dataOutputStream.writeBytes("Content-Disposition: form-data; name=\"uploaded_file" +
"\"; filename=\"" + FileName + "\"" + lineEnd);
dataOutputStream.writeBytes(lineEnd);
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1 * 1024 * 1024;
Log.e("message.......", "FileName...." + FileName);
//returns no. of bytes present in fileInputStream
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
//Thread.sleep(5000);
while (bytesRead > 0) {
//int percentage = (int) ((bytesRead / (float) size) * 100);
dataOutputStream.write(buffer, 0, bufferSize);
//dataOutputStream.flush(); //doesn't help
bytesAvailable = fileInputStream.available();
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
}
dataOutputStream.writeBytes(lineEnd);
dataOutputStream.writeBytes(twoHyphens + boundary + twoHyphens
+ lineEnd);
int code = urlConnection.getResponseCode();
StringBuilder result = new StringBuilder();
if (code == 200) {
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
String line;
while ((line = reader.readLine()) != null) {
result.append(line);
}
upload_success = result.toString();
}
} catch(SocketTimeoutException e) {
//e.printStackTrace();
if (urlConnection != null) {
urlConnection.disconnect();
cancel(true);
}
}
catch (UnsupportedEncodingException e) {
e.printStackTrace();
Log.e("message.......", "here....5");
} catch (ClientProtocolException e) {
e.printStackTrace();
Log.e("message.......", "here....6");
} catch (ConnectTimeoutException e) {
e.printStackTrace();
Log.e("message.......", "here....7");
}
catch (IOException ioException) {
ioException.printStackTrace();
Log.e("message.......", "here....2");
}
catch (Exception e) {
e.printStackTrace();
Log.e("message.......", "here....5");
if (failtoupload == false) {
failtoupload = true;
}
if (sendMail == true) {
sendMail = false;
}
if (UpdateDraft == true) {
UpdateDraft = false;
}
if (saveDraft == true) {
saveDraft = false;
}
Date dt = new Date();
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String savedDate = dateFormat.format(dt);
draftDB = new DraftDB(mContext);
if (mSelectedFilesList.size() == 1) {
attachments = join("", mSelectedFilesList);
if (attachments.equals("")) {
attachments = null;
}
}
else
{
attachments = join(", ", mSelectedFilesList);
}
if (attachments == null) {
if (mSelectedFilesList.size() == 1) {
attachments = join("", mSelectedFilesList);
}
else
{
attachments = join(", ", mSelectedFilesList);
}
}
String isImportant = "true";
String isRead = "unread";
String UpdateDB = null;
String draftID = null;
if (to == null) {
to = "";
}
if (bcc == null) {
bcc = "";
}
if (cc == null) {
cc = "";
}
if (subject == null) {
subject = "";
}
if (message == null) {
message = "";
}
if (draft_id != null) {
draftID = draft_id;
UpdateDB = "yes";
}
else
{
draftID = "";
UpdateDB = "no";
}
if (draftDB_id == 0) {
draftDB.insertDraft(from, to, cc, bcc, subject, message, attachments, isImportant, isRead, UpdateDB, draftID, savedDate);
draftDB_id = draftDB.getID();
}
else
{
int id = draftDB_id;
draftDB.updateDraft(id, from, to, cc, bcc, subject, message, attachments, isImportant, isRead, UpdateDB, draftID, savedDate);
}
else
{
int id = draftDB_id;
draftDB.updateDraft(id, from, to, cc, bcc, subject, message, attachments, isImportant, isRead, UpdateDB, draftID, savedDate);
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
Log.e("message.......", "here....6");
if (upload_success != null) {
if (upload_success.equals("success")) {
if (mSelectedFilesList.size() > 0) {
mSelectedFilesList.remove(0);
if (draft_id == null) {
new SaveDraft().execute();
}
else if (draft_id != null) {
if (attachment != null) {
if (mSelectedFilesList.size() >= 1) {
attid++;
for (int i = 0; i < mSelectedFilesList.size(); i++) {
String path = mSelectedFilesList.get(0);
FileName = path.substring(path.lastIndexOf("/") + 1);
attachment += " attid: " + String.valueOf(attid) + " filename: " + FileName;
}
}
}
Log.e("message........", "attachment......" + attachment);
new UpdateDrafts().execute();
}
if (mSelectedFilesList.size() >= 1) {
FilePath = mSelectedFilesList.get(0);
upload_File = new File(FilePath);
FileName = upload_File.getName();
new UploadFile().execute();
}
}
//Now time to check the upload_File
if (mSelectedFilesList.size() == 0) {
if (upload_File != null) {
upload_File = null;
}
if (FilePath != null) {
FilePath = null;
}
Log.e("message.......", "sendMail........." + sendMail);
}
if (upload_success != null) {
upload_success = null;
}
}
}
}
#Override
protected void onCancelled() {
super.onCancelled();
this.cancel(true);
}
}
What I am trying to do is when I select on the file and add more files on my mobile app, I want to call the UploadFile function instantly and connect to my server to upload the file in each time when I select on the file. If the server do not response for 10 seconds and the server is offline, I want to store the data in the sqlite database.
I have been told that I should use multi thread and I should also use retrofit. I am not sure if it would be possible to use HttpUrlConnection method with multi thread to connect to the server and upload the files.
Can you please show me an example of what is the best way I could use to get instantly call to a function and connect to the server using with HttpUrlConnection if that is possible??
You start already wrong with trying to get a real path for an uri.
Remove that code.
Then instead of opening a FileInputStream open an InputStream for the uri
InputStream is = getContentResolvet().openInputStream(uri);
I want to get the attached content of MMS like Image or Video/audio.
First I make this
static void getMmsContent(Context context, ArrayList<Mms> mmsArrayList) {
try {
for (Mms unMms : mmsArrayList) {
ContentResolver contentResolver = context.getContentResolver();
Uri uri = Uri.parse("content://mms/part");
String selection = Telephony.Mms.Part.MSG_ID + "=" + unMms.getId();
Cursor query = contentResolver.query(uri, null, selection, null, null);
if (query != null && query.moveToFirst()) {
do {
String name = query.getString(query.getColumnIndex("name"));
String type = query.getString(query.getColumnIndex("ct"));
String txt = query.getString(query.getColumnIndex(Telephony.Mms.Part.TEXT));
String data = query.getString(query.getColumnIndex(Telephony.Mms.Part._DATA));
if (!type.equals("application/smil")) {
String[] dataMms = {name, type, txt, data};
getContent(context, dataMms, unMms);
}
} while (query.moveToNext());
}
if (query != null) {
query.close();
}
}
} catch (Exception e) {
Log.d("Exception", e.toString());
}
}
This line give me the path to the location of the attached content.
String data = query.getString(query.getColumnIndex(Telephony.Mms.Part._DATA));
/data/user_de/0/com.android.providers.telephony/app_parts/PART_1555841710097_Screenshot_20190421-121445_Chrome1.jpg
So now i want to transform the image to a Bitmap to add it to a zip file.
static private void getContent(Context context, String[] dataMms, Mms unMms){
if (dataMms[1].equals("text/plain")) {
unMms.setCorps(dataMms[2]);
} else {
if ("image/jpeg".equals(dataMms[1]) || "image/bmp".equals(dataMms[1]) ||
"image/gif".equals(dataMms[1]) || "image/jpg".equals(dataMms[1]) ||
"image/png".equals(dataMms[1])) {
unMms.setTypeContenu(dataMms[1]);
Bitmap bitmap = null;
InputStream is = null;
try {
File source = new File(dataMms[3]);
is = new FileInputStream(source);
bitmap = BitmapFactory.decodeStream(is);
} catch (IOException e) {
Log.d("Exception", e.toString());
} finally {
if (is != null) {
try {
is.close();
} catch (IOException e) {
Log.d("Exception", e.toString());
}
}
}
if (bitmap != null) {
File file = new File(context.getApplicationInfo().dataDir + "/files/", dataMms[0]);
OutputStream Fout = null;
try {
Fout = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, Fout);
Fout.flush();
Fout.close();
} catch (FileNotFoundException e) {
Log.d("Exception", e.toString());
} catch (IOException e) {
Log.d("Exception", e.toString());
}
}
}
}
}
But my code Throw a Exception on new FileInputStream(source);
I got this
D/Exception: java.io.FileNotFoundException: /data/user_de/0/com.android.providers.telephony/app_parts/PART_1547316880687_Resized_20190112_191438_9422.jpeg (Permission denied)
I have the permissions and i have require the user permission.
<uses-permission android:name="android.permission.READ_SMS" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
So i change my code after the comment of CommonsWare to this :
static private void getContent(Context context, String[] dataMms, Mms unMms) {
if (dataMms[1].equals("text/plain")) {
unMms.setCorps(dataMms[2]);
} else {
if ("image/jpeg".equals(dataMms[1]) || "image/bmp".equals(dataMms[1]) ||
"image/gif".equals(dataMms[1]) || "image/jpg".equals(dataMms[1]) ||
"image/png".equals(dataMms[1])) {
unMms.setTypeContenu(dataMms[1]);
Uri partURI = Uri.parse("content://mms/part/" + dataMms[4]);
InputStream is = null;
Bitmap bitmap = null;
try {
is = context.getContentResolver().openInputStream(partURI);
bitmap = BitmapFactory.decodeStream(is);
} catch (IOException e) {
Log.d("Exception", e.toString());
} finally {
if (is != null) {
try {
is.close();
} catch (IOException e) {
Log.d("Exception", e.toString());
}
}
}
if (bitmap != null) {
File file = new File(context.getApplicationInfo().dataDir + "/files/", dataMms[0]);
OutputStream Fout = null;
try {
file.createNewFile();
Fout = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, Fout);
Fout.flush();
Fout.close();
} catch (FileNotFoundException e) {
Log.d("Exception", e.toString());
} catch (IOException e) {
Log.d("Exception", e.toString());
}
}
}
}
}
The tricky part is this :
Uri partURI = Uri.parse("content://mms/part/" + dataMms[4]);
my dataMms[4] is the id of the MMS Part, I get it from this line I put on getMmsContent() :
String id = query.getString(query.getColumnIndex("_id"));
This column give me the id of the part.
But there is no mention about this column in Android Developer documentation : https://developer.android.com/reference/android/provider/Telephony.Mms.Part.html
So I listed the columns with this code in getMmsContent() and I found it :
for (int i = 0; i < query.getColumnCount(); i++) {
Log.i("Column", query.getColumnName(i));
}
Now It's working !
Looking to add GPS location data to an image as it saves, as far as i'm aware this needs to be done after the outputStream closes. I've written the code and implemented it however no GPS location data is written. As far as i'm aware i have prepared all the relevant data that would be required for the EXIF Data.
GPS Converting Code
public String getLon(Location location) {
if (location == null) return "0/1,0/1,0/1000";
String[] degMinSec = Location.convert(location.getLongitude(), Location.FORMAT_SECONDS).split(":");
return degMinSec[0] + "/1," + degMinSec[1] + "/1," + degMinSec[2] + "/1000";
}
public String getLat(Location location) {
if (location == null) return "0/1,0/1,0/1000";
String[] degMinSec = Location.convert(location.getLatitude(), Location.FORMAT_SECONDS).split(":");
return degMinSec[0] + "/1," + degMinSec[1] + "/1," + degMinSec[2] + "/1000";
}
Code to save the Image
file = new File(Environment.getExternalStorageDirectory() + "/DCIM/GeoVista/" + UUID.randomUUID().toString() + ".jpg");
ImageReader.OnImageAvailableListener readerListener = new ImageReader.OnImageAvailableListener() {
#Override
public void onImageAvailable(ImageReader imageReader) {
Image image = null;
try {
image = reader.acquireLatestImage();
ByteBuffer buffer = image.getPlanes()[0].getBuffer();
byte[] bytes = new byte[buffer.capacity()];
buffer.get(bytes);
save(bytes);
storeGeoCoordsToImage(bytes);
save(bytes);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
{
if (image != null)
image.close();
}
}
}
private void save(byte[] bytes) throws IOException {
OutputStream outputStream = null;
try {
outputStream = new FileOutputStream(file);
outputStream.write(bytes);
} finally {
if (outputStream != null)
outputStream.close();
}
}
};
EXIF DATA CODE
public boolean storeGeoCoordsToImage(File file, Location location) {
// Avoid NullPointer
if (file == null || location == null) return false;
try {
ExifInterface exif = new ExifInterface(file.getAbsolutePath());
exif.setAttribute(ExifInterface.TAG_GPS_LATITUDE, getLat(location));
exif.setAttribute(ExifInterface.TAG_GPS_LATITUDE_REF, location.getLatitude() < 0 ? "S" : "N");
exif.setAttribute(ExifInterface.TAG_GPS_LONGITUDE, getLon(location));
exif.setAttribute(ExifInterface.TAG_GPS_LONGITUDE_REF, location.getLongitude() < 0 ? "W" : "E");
exif.saveAttributes();
} catch (IOException e) {
// do something
return false;
}
// Data was likely written. For sure no NullPointer.
return true;
}
Any Input would be greatly appreciated.
I am doing a function to download files to android device, works fine but I want to do that if the downloaded file exists already in the device will overwrite it. Here is my code:
class DownloadTask extends AsyncTask<String, Integer, String> {
private Context context;
private PowerManager.WakeLock mWakeLock;
public DownloadTask(Context context) {
this.context = context;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
// take CPU lock to prevent CPU from going off if the user
// presses the power button during download
PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
getClass().getName());
mWakeLock.acquire();
mProgressDialog.show();
}
#Override
protected void onProgressUpdate(Integer... progress) {
super.onProgressUpdate(progress);
// if we get here, length is known, now set indeterminate to false
mProgressDialog.setIndeterminate(false);
mProgressDialog.setMax(100);
mProgressDialog.setProgress(progress[0]);
}
#Override
protected void onPostExecute(String result) {
mWakeLock.release();
mProgressDialog.dismiss();
if (result != null){
this.finish();
}
else
{
Descargar.this.finish();
}
}
#Override
protected String doInBackground(String... sUrl) {
InputStream input = null;
HttpURLConnection connection = null;
for (i=0; i< sUrl.length; i++) {
try {
URL url = new URL(sUrl[i]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
// expect HTTP 200 OK, so we don't mistakenly save error report
// instead of the file
if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
return "Server returned HTTP " + connection.getResponseCode()
+ " " + connection.getResponseMessage();
}
// this will be useful to display download percentage
// might be -1: server did not report the length
int fileLength = connection.getContentLength();
// download the file
input = connection.getInputStream();
fOut = openFileOutput(i+".json",MODE_PRIVATE);
//fOut = new FileOutputStream("/aste/tiempobilbao.json");
byte data[] = new byte[4096];
long total = 0;
int count;
while ((count = input.read(data)) != -1) {
// allow canceling with back button
if (isCancelled()) {
input.close();
return null;
}
total += count;
// publishing the progress....
if (fileLength > 0) // only if total length is known
publishProgress((int) (total * 100 / fileLength));
fOut.write(data, 0, count);
}
} catch (Exception e) {
return e.toString();
} finally {
try {
if (fOut != null)
fOut.close();
if (input != null)
input.close();
} catch (IOException ignored) {
}
if (connection != null)
connection.disconnect();
}
}
return null;
}
}
If the file exist, delete it first.
you can delete file before starting download with below code :
File myFile = new File(fileName);
if(myFile.exists())
myFile.delete();
I would like to download a large pdf file with jsoup. I have try to change timeout and maxBodySize but the largest file I could download was about 11MB. I think if there is any way to do something like buffering. Below is my code.
public class Download extends Activity {
static public String nextPage;
static public Response file;
static public Connection.Response res;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
Bundle b = new Bundle();
b = getIntent().getExtras();
nextPage = b.getString("key");
new Login().execute();
finish();
}
private class Login extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... params) {
try {
res = Jsoup.connect("http://www.eclass.teikal.gr/eclass2/")
.ignoreContentType(true).userAgent("Mozilla/5.0")
.execute();
SharedPreferences pref = getSharedPreferences(
MainActivity.PREFS_NAME, MODE_PRIVATE);
String username1 = pref.getString(MainActivity.PREF_USERNAME,
null);
String password1 = pref.getString(MainActivity.PREF_PASSWORD,
null);
file = (Response) Jsoup
.connect("http://www.eclass.teikal.gr/eclass2/")
.ignoreContentType(true).userAgent("Mozilla/5.0")
.maxBodySize(1024*1024*10*2)
.timeout(70000*10)
.cookies(res.cookies()).data("uname", username1)
.data("pass", password1).data("next", nextPage)
.data("submit", "").method(Method.POST).execute();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
String PATH = Environment.getExternalStorageDirectory()
+ "/download/";
String name = "eclassTest.pdf";
FileOutputStream out;
try {
int len = file.bodyAsBytes().length;
out = new FileOutputStream(new File(PATH + name));
out.write(file.bodyAsBytes(),0,len);
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
I hope somebody could help me!
I think, it's better to download any binary file via HTTPConnection:
InputStream input = null;
OutputStream output = null;
HttpURLConnection connection = null;
try {
URL url = new URL("http://example.com/file.pdf");
connection = (HttpURLConnection) url.openConnection();
connection.connect();
// expect HTTP 200 OK, so we don't mistakenly save error report
// instead of the file
if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
return "Server returned HTTP " + connection.getResponseCode()
+ " " + connection.getResponseMessage();
}
// this will be useful to display download percentage
// might be -1: server did not report the length
int fileLength = connection.getContentLength();
// download the file
input = connection.getInputStream();
output = new FileOutputStream("/sdcard/file_name.extension");
byte data[] = new byte[4096];
int count;
while ((count = input.read(data)) != -1) {
output.write(data, 0, count);
}
} catch (Exception e) {
return e.toString();
} finally {
try {
if (output != null)
output.close();
if (input != null)
input.close();
} catch (IOException ignored) {
}
if (connection != null)
connection.disconnect();
}
Jsoup is for parsing and loading HTML pages, not binary files.