It saves empty when saving apk file to device - java

I set up HttpServer in Java. When the apk file is sent by the client, I want to save it to the device. However, when using the code below, it saves to the device in a empty way.
(0 bytes when I say empty) Where am I doing wrong?
Note:
In the log in the code, I tested that the apk file was sent properly by the client. Values ​​such as size, byte, apk name are coming in properly.
class postApkFile implements HttpHandler {
#RequiresApi(api = Build.VERSION_CODES.O)
#Override
public void handle(HttpExchange he) throws IOException {
he.getResponseHeaders().add("Access-Control-Allow-Origin", "*");
if (he.getRequestMethod().equalsIgnoreCase("OPTIONS")) {
he.getResponseHeaders().add("Access-Control-Allow-Methods", "GET, OPTIONS");
he.getResponseHeaders().add("Access-Control-Allow-Headers", "Content-Type,Authorization");
he.sendResponseHeaders(204, -1);
return;
}
DiskFileItemFactory d = new DiskFileItemFactory();
try {
ServletFileUpload up = new ServletFileUpload(d);
List<FileItem> result = up.parseRequest(new RequestContext() {
#Override
public String getCharacterEncoding() {
return "UTF-8";
}
#Override
public int getContentLength() {
return 0; //tested to work with 0 as return
}
#Override
public String getContentType() {
return he.getRequestHeaders().getFirst("Content-type");
}
#Override
public InputStream getInputStream() throws IOException {
return he.getRequestBody();
}
});
InputStream inputStream = he.getRequestBody();
String configXmlFilePath = Environment.getExternalStorageDirectory() + "test/configXml/test.apk";
File apkFile = new File(configXmlFilePath);
FileOutputStream outputStream = new FileOutputStream(apkFile);
he.getResponseHeaders().add("Content-type", "text/plain");
he.sendResponseHeaders(200, 0);
OutputStream os = he.getResponseBody();
byte[] buffer = new byte[1024];
Log.i(HttpServerManager.getHttpServerManager().TAG, "buffer1");
int bytesRead;
Log.i(HttpServerManager.getHttpServerManager().TAG, "bufferread");
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
inputStream.close();
outputStream.close();
for (FileItem fi : result) {
os.write(fi.getName().getBytes());
os.write("\r\n".getBytes());
Log.i(HttpServerManager.getHttpServerManager().TAG, "File-Item: " + fi.getFieldName() + " = " + fi.getName() + " get size " + fi.getSize() );
}
os.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}

Writing the while block after the for loop solved my problem.
class postApkFile implements HttpHandler {
#RequiresApi(api = Build.VERSION_CODES.O)
#Override
public void handle(HttpExchange he) throws IOException {
he.getResponseHeaders().add("Access-Control-Allow-Origin", "*");
if (he.getRequestMethod().equalsIgnoreCase("OPTIONS")) {
he.getResponseHeaders().add("Access-Control-Allow-Methods", "GET, OPTIONS");
he.getResponseHeaders().add("Access-Control-Allow-Headers", "Content-Type,Authorization");
he.sendResponseHeaders(204, -1);
return;
}
DiskFileItemFactory d = new DiskFileItemFactory();
try {
ServletFileUpload up = new ServletFileUpload(d);
List<FileItem> result = up.parseRequest(new RequestContext() {
#Override
public String getCharacterEncoding() {
return "UTF-8";
}
#Override
public int getContentLength() {
return 0; //tested to work with 0 as return
}
#Override
public String getContentType() {
return he.getRequestHeaders().getFirst("Content-type");
}
#Override
public InputStream getInputStream() throws IOException {
return he.getRequestBody();
}
});
String configXmlFilePath = Environment.getExternalStorageDirectory() + "test/configXml/test.apk";
File apkFile = new File(configXmlFilePath);
he.getResponseHeaders().add("Content-type", "text/plain");
he.sendResponseHeaders(200, 0);
OutputStream os = he.getResponseBody();
InputStream inputStream = null;
for (FileItem fi : result) {
os.write(fi.getName().getBytes());
os.write("\r\n".getBytes());
inputStream = fi.getInputStream();
Log.i(HttpServerManager.getHttpServerManager().TAG, "File-Item: " + fi.getFieldName() + " = " + fi.getName());
}
FileOutputStream outputStream = new FileOutputStream(apkFile);
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
Log.i(HttpServerManager.getHttpServerManager().TAG, "os.Close ve outputStream.close");
os.close();
inputStream.close();
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}

Related

transfering files android studio

I want to transfer files between 2 android mobiles.
This is sender
class BackgroundTask extends AsyncTask<String, Void, String> {
String ipaddress , filepath;
#Override
protected String doInBackground(String... params) {
ipaddress =params[0];
filepath=params[1];
try {
File file = new File(Environment.getExternalStorageDirectory(),filepath);
Socket socket = new Socket(ipaddress,5321);
BufferedOutputStream bos = new BufferedOutputStream(socket.getOutputStream());
DataOutputStream dos = new DataOutputStream(bos);
long length = file.length();
dos.writeLong(length);
String name = file.getName();
dos.writeUTF(name);
FileInputStream fis = new FileInputStream(file);
BufferedInputStream bis = new BufferedInputStream(fis);
int theByte = 0;
while((theByte = bis.read()) != -1) bos.write(theByte);
bis.close();
dos.close();
} catch (IOException e) {
;
}
return null;
}
}
and this is receiver code :
#Override
public void run() {
try {
ss = new ServerSocket(5321);
handler.post(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(), "waiting for connecting ..",Toast.LENGTH_LONG).show();
}
});
while (true){
mysocket = ss.accept();
handler.post(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(), "connected:" + massage,Toast.LENGTH_LONG).show();
}
});
BufferedInputStream bis = new BufferedInputStream(mysocket.getInputStream());
DataInputStream dis = new DataInputStream(bis);
long fileLength = dis.readLong();
String fileName = dis.readUTF();
String downloadfolderpath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getPath();
File files = new File(downloadfolderpath + "/" + fileName);
FileOutputStream fos = new FileOutputStream(files);
BufferedOutputStream bos = new BufferedOutputStream(fos);
for(int j = 0; j < fileLength; j++) bos.write(bis.read());
bos.close();
dis.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
AND THIS CODE TO GET FILE PATH (NOT SURE ABOUT THE RESULT OF IT)
Intent.ACTION_GET_CONTENT >>
AND ON ACTIVITY RESULT I GET THIS VALUE
intent.putExtra("filename", data.getData().getPath());
Any help

How to upload video in android using volley

I am trying to upload a video on the server, I didn't anything on this, please suggest
I can upload the text, that's working,
RequestQueue requestQueue = Volley.newRequestQueue(mContext);
StringRequest stringRequest = new StringRequest(Request.Method.POST, "http://54.146.132.94/webservices/target_response",
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Toast.makeText(mContext, "" + response, Toast.LENGTH_SHORT).show();
Log.i("error", response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(mContext, "" + error.toString(), Toast.LENGTH_SHORT).show();
Log.i("error", error.toString());
}
}) {
#Override
protected Map<String, String> getParams() {
// Posting parameters to login url
Map<String, String> params = new HashMap<String, String>();
params.put("I_trails", String.valueOf(itr));
params.put("E_trails", String.valueOf(et));
params.put("D_trails", String.valueOf(dt));
params.put("N_trails", String.valueOf(nt));
params.put("user_id", String.valueOf(get_id));
params.put("target_id", String.valueOf(get_target_id));
params.put("session_date", date);
params.put("data_mode", data_mode);
params.put("mode", mode);
params.put("link", link);
// params.put("video", selectedPath);
params.put("time", time_upload_real);
params.put("location_id", LocID);
params.put("No_of_trails", String.valueOf(notr));
/*params.put("comment", my_comment);*/
return params;
}
};
// Adding the StringRequest object into requestQueue.
requestQueue.add(stringRequest);
here the code to upload video, please let me know how to upload this video with the data, that I am uploading.
if (null != selectedPath && !selectedPath.isEmpty()){
Toast.makeText(mContext, "selected path: "+selectedPath, Toast.LENGTH_SHORT).show();
new Thread(new Runnable() {
#Override
public void run() {
//creating new thread to handle Http Operations
uploadFile(selectedPath);
}
}).start();
then,
public int uploadFile(final String selectedPath){
int serverResponseCode = 0;
HttpURLConnection connection;
DataOutputStream dataOutputStream;
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
int bytesRead,bytesAvailable,bufferSize;
byte[] buffer;
int maxBufferSize = 1 * 1024 * 1024;
File selectedFile = new File(selectedPath);
try {
FileInputStream fileInputStream = new FileInputStream(selectedFile);
URL url = new URL("http://54.146.132.94/webservices/target_response");
connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);//Allow Inputs
connection.setDoOutput(true);//Allow Outputs
connection.setUseCaches(false);//Don't use a cached Copy
connection.setRequestMethod("POST");
connection.setRequestProperty("Connection", "Keep-Alive");
connection.setRequestProperty("ENCTYPE", "multipart/form-data");
connection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
connection.setRequestProperty("video",selectedPath);
//creating new dataoutputstream
dataOutputStream = new DataOutputStream(connection.getOutputStream());
//writing bytes to data outputstream
dataOutputStream.writeBytes(twoHyphens + boundary + lineEnd);
dataOutputStream.writeBytes("Content-Disposition: form-data; name=\"video\";filename=\""
+ selectedPath + "\"" + lineEnd);
dataOutputStream.writeBytes(lineEnd);
//returns no. of bytes present in fileInputStream
bytesAvailable = fileInputStream.available();
//selecting the buffer size as minimum of available bytes or 1 MB
bufferSize = Math.min(bytesAvailable,maxBufferSize);
//setting the buffer as byte array of size of bufferSize
buffer = new byte[bufferSize];
//reads bytes from FileInputStream(from 0th index of buffer to buffersize)
bytesRead = fileInputStream.read(buffer,0,bufferSize);
//loop repeats till bytesRead = -1, i.e., no bytes are left to read
while (bytesRead > 0){
//write the bytes read from inputstream
dataOutputStream.write(buffer,0,bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable,maxBufferSize);
bytesRead = fileInputStream.read(buffer,0,bufferSize);
}
dataOutputStream.writeBytes(lineEnd);
dataOutputStream.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
serverResponseCode = connection.getResponseCode();
String serverResponseMessage = connection.getResponseMessage();
//closing the input and output streams
fileInputStream.close();
dataOutputStream.flush();
dataOutputStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (ProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// dialog.dismiss();
return serverResponseCode;
}
Intent intent = new Intent();
intent.setType("video/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Complete action using"), PICK_FROM_GALLERY);
and after selecting video
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode != RESULT_OK) return;
if (requestCode == PICK_FROM_GALLERY) {
Uri aa = data.getData();
mVideoURI = Uri.parse(String.valueOf(aa));
}
}
dont forget to use private Uri mVideoURI;
at top
inside your post volley method use :
#Override
protected Map<String, DataPart> getByteData() {
Map<String, DataPart> params = new HashMap<>();
/// photo field in link
if (mVideoURI != null) {
params.put("video", new DataPart("file_avatar.mp4", UploadHelper.getFileDataFromDrawable(getActivity(), mVideoURI)));
}
return params;
}
UPDATE
1- CREATE BroadcastHelper CLASS :
public class BroadcastHelper {
public static final String BROADCAST_EXTRA_METHOD_NAME = "INPUT_METHOD_CHANGED";
public static final String ACTION_NAME = "hassan.scott";
private static final String UPDATE_LOCATION_METHOD = "update";
public static void sendInform(Context context, String method) {
Intent intent = new Intent();
intent.setAction(ACTION_NAME);
intent.putExtra(BROADCAST_EXTRA_METHOD_NAME, method);
try {
context.sendBroadcast(intent);
} catch (Exception e) {
e.printStackTrace();
}
}
public static void sendInform(Context context, String method, Intent intent) {
intent.setAction(ACTION_NAME);
intent.putExtra(BROADCAST_EXTRA_METHOD_NAME, method);
try {
context.sendBroadcast(intent);
} catch (Exception e) {
e.printStackTrace();
}
}
}
2- Send intent from your adapter
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent url = new Intent("url");
url ("url_adapter",item.get(position).getURL());
BroadcastHelper.sendInform(context,"url",url);
}
});
3- in your fragment this use :
Receiver receiver;
boolean isReciverRegistered = false;
#Override
public void onResume() {
super.onResume();
if (receiver == null) {
receiver = new Receiver();
IntentFilter filter = new IntentFilter(BroadcastHelper.ACTION_NAME);
getActivity().registerReceiver(receiver, filter);
isReciverRegistered = true;
}
}
#Override
public void onDestroy() {
if (isReciverRegistered) {
if (receiver != null)
getActivity().unregisterReceiver(receiver);
}
super.onDestroy();
}
private class Receiver extends BroadcastReceiver {
#Override
public void onReceive(Context arg0, Intent arg1) {
Log.v("r", "receive " + arg1.getStringExtra(BroadcastHelper.BROADCAST_EXTRA_METHOD_NAME));
String methodName = arg1.getStringExtra(BroadcastHelper.BROADCAST_EXTRA_METHOD_NAME);
if (methodName != null && methodName.length() > 0) {
Log.v("receive", methodName);
switch (methodName) {
case "url":
/* call post method here */
default:
break;
}
}
}
}
UploadHelper Class :
public class UploadHelper {
/**
* Turn drawable resource into byte array.
*
* #param context parent context
* #param id drawable resource id
* #return byte array
*/
public static byte[] getFileDataFromDrawable(Context context, int id) {
Drawable drawable = ContextCompat.getDrawable(context, id);
Bitmap bitmap = ((BitmapDrawable) drawable).getBitmap();
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, byteArrayOutputStream);
return byteArrayOutputStream.toByteArray();
}
/**
* Turn drawable into byte array.
*
* #return byte array
*/
public static byte[] getFileDataFromDrawable(Context context, Uri uri) {
// Bitmap bitmap = ((BitmapDrawable) drawable).getBitmap();
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
try {
InputStream iStream = context.getContentResolver().openInputStream(uri);
int bufferSize = 2048;
byte[] buffer = new byte[bufferSize];
// we need to know how may bytes were read to write them to the byteBuffer
int len = 0;
if (iStream != null) {
while ((len = iStream.read(buffer)) != -1) {
byteArrayOutputStream.write(buffer, 0, len);
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// bitmap.compress(Bitmap.CompressFormat.JPEG, 100, byteArrayOutputStream);
return byteArrayOutputStream.toByteArray();
}
}
Volley wasn't really meant for video uploading. It is better suited to large in number - small in size uploads/downloads. I would recommend using a different method to upload your video.
Volley is not suitable for large download or streaming operations,
since Volley holds all responses in memory during parsing. For large
download operations, consider using an alternative like
DownloadManager.*
Taken from https://developer.android.com/training/volley/

Android how to download zip file using soap liabrary

I want to download zip file from server by using ksoap liabry.I am getting data in base64 please give solution that how to convert base64 and save it as zip file
byte[] bytes;
byte[] data = result.getBytes("UTF-8");
File outputFile = new File(mediaStorageDir.getAbsolutePath(), + "filename.zip");
new FileOutputStream(outputFile);
bytes = Base64.decode(data, Base64.DEFAULT);
File filepath = new File(Environment.getExternalStorageDirectory(), "Folder/" + "filename.zip");
OutputStream pdffos = new FileOutputStream(filepath);
pdffos.write(bytes);
pdffos.flush();
pdffos.close();
This Code help me to downlad apk and store to sd card.
This may help you also..
public class SaveInBackground extends AsyncTask<String,Integer,String> {
View v;
OutputValue ov;
Boolean isError= false;
public SaveInBackground(View v,OutputValue ov){
this.v = v;
this.ov = ov;
}
#Override
protected void onPreExecute(){
Message.setText("Downloading...");
isToLoop =true;
new Thread(new Runnable() {
#Override
public void run() {
while (isToLoop) {
SystemClock.sleep(500);
runOnUiThread(new Runnable() {
#Override
public void run() {
int count = bar.getProgress() + 1;
bar.setProgress(count);
}
});
if(isToLoop)
break;
}
}
}).start();
}
#Override
protected void onProgressUpdate(Integer... values) {
bar.setProgress(values[0]);
}
#Override
protected String doInBackground(String... params) {InputStream input = null;
OutputStream output = null;
HttpURLConnection connection = null;
try {
URL url = new URL(Globle.Infosoft_serverLink.replace("/Service.asmx/","")+ov.url);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
isError = true;
return "Server returned HTTP " + connection.getResponseCode()
+ " " + connection.getResponseMessage();
}
int fileLength = connection.getContentLength();
input = connection.getInputStream();
//publishProgress(80);
String path = Environment.getExternalStorageDirectory()+"/"+ov.Name+".apk";
output = new FileOutputStream(path );
byte data[] = new byte[4096];
long total = 0;
int count;
while ((count = input.read(data)) != -1) {
total += count;
if (fileLength > 0) // only if total length is known
publishProgress((int) (total * 100 / fileLength));
output.write(data, 0, count);
}
return path;
}
catch (Exception e) {
isError =true;
Snackbar.make(v,"Error while accessing storage.",Snackbar.LENGTH_LONG).show();
return null;
}finally {
try {
if (output != null)
output.close();
if (input != null)
input.close();
} catch (IOException ignored) {
}
if (connection != null)
connection.disconnect();
}
}
#Override
protected void onPostExecute(String result){
if(!isError) {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(new File(result)), "application/vnd.android.package-archive");
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
Message.setText("Downloaded");
reset(v);
}
}

Download mp4 from server and save it to sdcard

I simply want to download mp4 or .3gp files from server to android device. I have tried multiple ways to achieve but in some cases it gives IOException and some time give ProtocolException
First Method to download Video using DownloadVideoTask.class
public class DownloadVideoTask extends AsyncTask<String, Integer, Boolean>
{
String nameOfSong;
Context context;
Boolean flage = true;
ProgressDialog progressDialog2;
#SuppressLint("InlinedApi")
public DownloadVideoTask(Context context,String trackTitle)
{
this.context = context;
nameOfSong = trackTitle;
}
#Override
protected void onPreExecute()
{
super.onPreExecute();
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
{
progressDialog2 = new ProgressDialog(context, AlertDialog.THEME_HOLO_LIGHT);
}
else
{
progressDialog2 = new ProgressDialog(context);
}
progressDialog2.setIndeterminate(false);
progressDialog2.setMax(100);
progressDialog2.setTitle("Please wait...");
try
{
progressDialog2.setMessage("Downloding.. " + nameOfSong.substring(0, 20));
}
catch (Exception e)
{
progressDialog2.setMessage("Downloding Song...." );
}
progressDialog2.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progressDialog2.show();
}
#Override
protected Boolean doInBackground(String... params)
{
/* String trackTitle = params[0];
nameOfSong = trackTitle;
*/
String trackUrl = params[0];
try
{
File root;// = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
if(Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB)
{
root = Environment.getExternalStorageDirectory();
}
else
{
root = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
}
File dir = new File(root.getAbsolutePath() + "/XarDownloder");
if (dir.exists() == false)
{
dir.mkdirs();
}
URL url = new URL(trackUrl);
File file = new File(dir, nameOfSong);
URLConnection urlConnection = url.openConnection();
int fileLength = urlConnection.getContentLength();//ye statement inputStream k bad likhi thi
InputStream inputStream = urlConnection.getInputStream();
OutputStream outputStream = new FileOutputStream(
root.getAbsolutePath() + "/XarDownloder/" + nameOfSong
+ ".mp4");
byte data[] = new byte[1024];
long total = 0;
int count;
while ((count = inputStream.read(data)) != -1)
{
total += count;
// publishing the progress....
publishProgress((int) (total * 100 / fileLength));
outputStream.write(data, 0, count);
}
outputStream.flush();
outputStream.close();
inputStream.close();
try
{
if(Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB)
{
context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED,
Uri.parse("file://"+ Environment.getExternalStorageDirectory())));
}
else
{
context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED,Uri.parse("file://" + Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MUSIC))));
}
context.sendBroadcast(new Intent(
Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri
.fromFile(file)));
}
catch (Exception e)
{
}
return true;
}
catch (IOException e)
{
flage = false;
e.printStackTrace();
}
return false;
}
#Override
protected void onPostExecute(Boolean result)
{
super.onPostExecute(result);
if (result)
{
try
{
Toast.makeText(context,
nameOfSong.substring(0, 30) + "Downloaded...",
Toast.LENGTH_LONG).show();
}
catch (Exception e)
{
Toast.makeText(context,
"Song Downloaded...",
Toast.LENGTH_LONG).show();
}
}
else
{
Toast.makeText(context, "Sorry, song is not downloadable",
Toast.LENGTH_LONG).show();
}
progressDialog2.dismiss();
}
#Override
protected void onProgressUpdate(Integer... values)
{
super.onProgressUpdate(values);
progressDialog2.setProgress(values[0]);
}
}
Second Method using DownloadFile
public class DownloadFile extends AsyncTask<String, Integer, String>
{
String videoToDownload = "http://r2---sn-u2oxu-f5f6.googlevideo.com/videoplayback?expire=1438261718&fexp=901816,9405637,9407538,9407942,9408513,9408710,9409172,9413020,9414764,9414856,9414935,9415365,9415485,9416126,9416355,9417009,9417719,9418201,9418204&id=d813f7f3bef428da&mn=sn-u2oxu-f5f6&mm=31&mime=video/mp4&upn=82UaibRK7EM&itag=18&pl=24&dur=148.189&ip=167.114.5.145&key=yt5&ms=au&mt=1438239687&mv=u&source=youtube&ipbits=0&pcm2cms=yes&sparams=dur,id,ip,ipbits,itag,lmt,mime,mm,mn,ms,mv,pcm2cms,pl,ratebypass,source,upn,expire&lmt=1428049239028653&signature=39087CBD9BDC9EBD612CA0E8E82AC692B427FFE3.18C23CD0AEC8410CFBE4F35F532199DFF21E7DFA&ratebypass=yes&sver=3&signature=&title=How+To+Train+Your+Dragon+2+Official+Trailer+%231+%282014%29+-+Animation+Sequel+HD&filename=How_To_Train_Your_Dragon_2_Official_Trailer_1_2014__Animation_Sequel_HD.mp4";
public DownloadFile()
{
}
#Override
protected String doInBackground(String... params)
{
int count;
try
{
mp4load(videoToDownload);
}
catch (Exception e)
{
// TODO: handle exception
}
/*try
{
URL url = new URL(videoToDownload);
URLConnection conexion = url.openConnection();
conexion.connect();
// this will be useful so that you can show a tipical 0-100%
// progress bar
int lenghtOfFile = conexion.getContentLength();
// downlod the file
InputStream input = new BufferedInputStream(url.openStream());
OutputStream output = new FileOutputStream("/sdcard/xarwere/firstdownload.mp4");
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1)
{
total += count;
// publishing the progress....
publishProgress((int) (total * 100 / lenghtOfFile));
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
}
catch (Exception e)
{
e.printStackTrace();
}*/
return null;
}
public void mp4load(String urling)
{
try
{
URL url = new URL(urling);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("GET");
//c.setDoOutput(true);
con.connect();
String PATH = Environment.getExternalStorageDirectory()
+ "/download/";
//Log.v(LOG_TAG, "PATH: " + PATH);
File file = new File(PATH);
file.mkdirs();
String fileName = "test.mp4";
File outputFile = new File(file, fileName);
if (!outputFile.exists())
{
outputFile.createNewFile();
}
FileOutputStream fos = new FileOutputStream(outputFile);
int status = con.getResponseCode();//my doctory
InputStream is = con.getInputStream();
byte[] buffer = new byte[1024];
int len1 = 0;
while ((len1 = is.read(buffer)) != -1) {
fos.write(buffer, 0, len1);
}
fos.close();
is.close();
}
catch (MalformedURLException e)
{
e.printStackTrace();
}
catch (ProtocolException e)
{
e.printStackTrace();
}
catch (IOException e1)
{
e1.printStackTrace();
}
}
}
Where videoToDownload in DownloadFile.class is the URLi want to download. but at inputStream it gives exception.
And I call these AsyncTask like
new DownloadFile().execute();
new DownloadVideoTask(TestingActivity.this, "nameofsong").execute("http://r2---sn-u2oxu-f5f6.googlevideo.com/videoplayback?expire=1438261718&fexp=901816,9405637,9407538,9407942,9408513,9408710,9409172,9413020,9414764,9414856,9414935,9415365,9415485,9416126,9416355,9417009,9417719,9418201,9418204&id=d813f7f3bef428da&mn=sn-u2oxu-f5f6&mm=31&mime=video/mp4&upn=82UaibRK7EM&itag=18&pl=24&dur=148.189&ip=167.114.5.145&key=yt5&ms=au&mt=1438239687&mv=u&source=youtube&ipbits=0&pcm2cms=yes&sparams=dur,id,ip,ipbits,itag,lmt,mime,mm,mn,ms,mv,pcm2cms,pl,ratebypass,source,upn,expire&lmt=1428049239028653&signature=39087CBD9BDC9EBD612CA0E8E82AC692B427FFE3.18C23CD0AEC8410CFBE4F35F532199DFF21E7DFA&ratebypass=yes&sver=3&signature=&title=How+To+Train+Your+Dragon+2+Official+Trailer+%231+%282014%29+-+Animation+Sequel+HD&filename=How_To_Train_Your_Dragon_2_Official_Trailer_1_2014__Animation_Sequel_HD.mp4");
I slighthly modified your code, but it downloads the file well. Did you add the internet permission?
public class DownloadFile extends AsyncTask<String, Integer, String> {
String videoToDownload = "http://r2---sn-u2oxu-f5f6.googlevideo.com/videoplayback?expire=1438261718&fexp=901816,9405637,9407538,9407942,9408513,9408710,9409172,9413020,9414764,9414856,9414935,9415365,9415485,9416126,9416355,9417009,9417719,9418201,9418204&id=d813f7f3bef428da&mn=sn-u2oxu-f5f6&mm=31&mime=video/mp4&upn=82UaibRK7EM&itag=18&pl=24&dur=148.189&ip=167.114.5.145&key=yt5&ms=au&mt=1438239687&mv=u&source=youtube&ipbits=0&pcm2cms=yes&sparams=dur,id,ip,ipbits,itag,lmt,mime,mm,mn,ms,mv,pcm2cms,pl,ratebypass,source,upn,expire&lmt=1428049239028653&signature=39087CBD9BDC9EBD612CA0E8E82AC692B427FFE3.18C23CD0AEC8410CFBE4F35F532199DFF21E7DFA&ratebypass=yes&sver=3&signature=&title=How+To+Train+Your+Dragon+2+Official+Trailer+%231+%282014%29+-+Animation+Sequel+HD&filename=How_To_Train_Your_Dragon_2_Official_Trailer_1_2014__Animation_Sequel_HD.mp4";
#Override
protected String doInBackground(String... params) {
int count;
try {
mp4load(videoToDownload);
} catch (Exception e) {
// TODO: handle exception
}
return null;
}
public void mp4load(String urling) {
try {
URL url = new URL(urling);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("GET");
//c.setDoOutput(true);
con.connect();
String downloadsPath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getAbsolutePath();
String fileName = "test.mp4";
File outputFile = new File(downloadsPath, fileName);
if (!outputFile.exists()) {
outputFile.createNewFile();
}
FileOutputStream fos = new FileOutputStream(outputFile);
int status = con.getResponseCode();
InputStream is = con.getInputStream();
byte[] buffer = new byte[1024];
int len1 = 0;
while ((len1 = is.read(buffer)) != -1) {
fos.write(buffer, 0, len1);
}
fos.close();
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

getting blank pdf on implementing pdf reader in project

i am trying to implement a pdf reader via a pdf library from git hub https://github.com/jblough/Android-Pdf-Viewer-Library but when i implement the code.. all i am getting is a blank page.. the url is correct the pdf has content and this is similar to this q .. Example of code to implement a PDF reader
my code consist of multiple methods, the main method is used to select the which pdf should be chosen to display. then the pdf name is passed on to method "copyreadassets"
public void CopyReadAssets(String url) {
AssetManager assetManager = getApplicationContext().getAssets();
InputStream in = null;
OutputStream out = null;
File file = new File(getApplicationContext().getFilesDir(), url);
try {
in = assetManager.open(url);
out = getApplicationContext().openFileOutput(file.getName(),
Context.MODE_WORLD_READABLE);
copyFile(in, out);
in.close();
in = null;
out.flush();
out.close();
out = null;
}
catch (Exception e) {
Log.e("tag", e.getMessage());
}
String path = "file://" + getApplicationContext().getFilesDir() + "/"+url;
openPdfIntent(path); }
the openpdfintentmethod is used to open the values
private void openPdfIntent(String path) {
// TODO Auto-generated method stub
try {
final Intent intent = new Intent(Question_Point_Main.this, Pdf.class);
intent.putExtra(PdfViewerActivity.EXTRA_PDFFILENAME, path);
startActivity(intent);
} catch (Exception e) {
e.printStackTrace();
}
}
pdf.class contains the following..
public class Pdf extends Activity{
public int getPreviousPageImageResource() {
return R.drawable.left_arrow; }
public int getNextPageImageResource() {
return R.drawable.right_arrow; }
public int getZoomInImageResource() {
return R.drawable.zoom_in; }
public int getZoomOutImageResource() {
return R.drawable.zoom_out; }
public int getPdfPasswordLayoutResource() {
return R.layout.pdf_file_password; }
public int getPdfPageNumberResource() {
return R.layout.dialog_pagenumber; }
public int getPdfPasswordEditField() {
return R.id.etPassword; }
public int getPdfPasswordOkButton() {
return R.id.btOK; }
public int getPdfPasswordExitButton() {
return R.id.btExit; }
public int getPdfPageNumberEditField() {
return R.id.pagenum_edit; }
}
In your AndroidManifest.xml file
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<activity android:name="com.example.readassetpdf.myPDFActivity"></activity>
in your case activity is pdf class
<activity android:name="com.example.readassetpdf.pdf"></activity>
and use following method
public void CopyReadAssets(String url) {
AssetManager assetManager = getApplicationContext().getAssets();
InputStream in = null;
OutputStream out = null;
File file = new File(getApplicationContext().getFilesDir(), url);
try {
in = assetManager.open(url);
//out = getApplicationContext().openFileOutput(file.getName(),
//Context.MODE_WORLD_READABLE);
out=new FileOutputStream(Environment.getExternalStorageDirectory().getAbsolutePath()+"/mypdf.pdf");
copyFile(in, out);
in.close();
in = null;
out.flush();
out.close();
out = null;
}
catch (Exception e) {
Log.e("tag", e.getMessage());
}
String path = Environment.getExternalStorageDirectory().getAbsolutePath()+"/mypdf.pdf";
openPdfIntent(path);
}
and call it as below
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.activity_main);
CopyReadAssets("mypdf.pdf");
}
And the function copyfile is as below
private void copyFile(InputStream in, OutputStream out) throws IOException{
byte[] buffer = new byte[1024];
int read;
while ((read = in.read(buffer)) != -1) {
out.write(buffer, 0, read);
}
}
The replacement is
out = getApplicationContext().openFileOutput(file.getName(),
Context.MODE_WORLD_READABLE);
to
out=new FileOutputStream(Environment.getExternalStorageDirectory().getAbsolutePath()+"/mypdf.pdf");

Categories