download errors, can't open files - android

My app has to connect to google drive. The connection works fine.
I can see all the files in the drive. The download of the files works fine.
Unfortunately when I try to open it the files are corrupted or I can't open them at all. Does anyone know a solution for this problem ??
enter code here
URL url = new URL(fileURL);
HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
int responseCode = httpConn.getResponseCode();
// always check HTTP response code first
if (responseCode == HttpURLConnection.HTTP_OK) {
String fileName = "";
String disposition = httpConn.getHeaderField("Content-Disposition");
String contentType = httpConn.getContentType();
int contentLength = httpConn.getContentLength();
if (disposition != null) {
// extracts file name from header field
int index = disposition.indexOf("filename=");
if (index > 0) {
fileName = disposition.substring(index + 10,
disposition.length() - 1);
}
} else {
// extracts file name from URL
fileName = fileURL.substring(fileURL.lastIndexOf("/") + 1,
fileURL.length());
}
System.out.println("Content-Type = " + contentType);
System.out.println("Content-Disposition = " + disposition);
System.out.println("Content-Length = " + contentLength);
System.out.println("fileName = " + fileName);
fileName = mr.getTitle();
// opens input stream from the HTTP connection
// URLConnection connection = url.openConnection();
String saveFilePath = saveDir + File.separator + fileName;
InputStream inputStream = httpConn.getInputStream();
FileOutputStream outputStream = new
FileOutputStream(saveFilePath);
// opens an output stream to save into file
int bytesRead = 0;
// int read;
byte[] buffer = new byte[16384];
// while ((bytesRead = inputStream.read(buffer)) > 0) {
// outputStream.write(buffer, 0, bytesRead);
// }
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
outputStream.flush();
outputStream.close();
inputStream.close();
System.out.println("File downloaded");
} else {
System.out
.println("No file to download. Server replied HTTP code: "
+ responseCode);
}
httpConn.disconnect();

It's problem between your file length and byte buffer. For quickly, please change to and retry
byte[] buffer = new byte[1024];
or you could get the length of input stream then create buffer
long streamLength = inputStream.available();
byte[] buffer = new byte[streamLength];
Have fun!

Related

How to get PDF file from HttpUrlConnection response in Android Java?

I am getting pdf file in response of API, I am using HttpUrlConnection (Android Java). I am unable to get pdf file from the response.
My code to get response is:
URL url = new URL(RESULT_DOWNLOAD_URL);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setAllowUserInteraction(false);
connection.setRequestProperty("Connection", "Keep-Alive");
connection.setConnectTimeout(90000);
connection.setReadTimeout(90000);
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/pdf");
connection.setRequestProperty("Accept", "application/pdf");
connection.setRequestProperty("access-token", resultAccessToken);
connection.setChunkedStreamingMode(1024);
connection.connect();
JSONObject jsonObject = new JSONObject();
jsonObject.put("reference",reference);
DataOutputStream os = new DataOutputStream(connection.getOutputStream());
byte[] payload = jsonObject.toString().getBytes(StandardCharsets.UTF_8);
int progressPercent = 0;
int offset = 0;
int bufferLength = payload.length / 100;
while(progressPercent < 100) {
os.write(payload, offset, bufferLength);
offset += bufferLength;
++progressPercent;
this.publishProgress(progressPercent);
}
os.write(payload, offset, payload.length % 100);
os.flush();
os.close();
int responseCode = connection.getResponseCode();
if ((responseCode >= HttpURLConnection.HTTP_OK)
&& responseCode < 300) {
inputStream = connection.getInputStream();
resultResponse = inputStreamToString(inputStream);
Log.d(TAG, "Response : " + resultResponse);
}
private static String inputStreamToString(InputStream inputStream) throws IOException {
StringBuilder out = new StringBuilder();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
out.append(line);
}
reader.close();
return out.toString();
}
Response is like(for understanding, I converted it in string form):
I want to download file from this response, response is returning pdf file.
Add this code...
int responseCode = connection.getResponseCode();
if ((responseCode >= HttpURLConnection.HTTP_OK)
&& responseCode < 300) {
inputStream = connection.getInputStream();
String FolderPath = "Images/"
File folder = null;
if(Build.VERSION.SDK_INT >= 29){ //Build.VERSION_CODES.R
folder = new File(context.getFilesDir() + "/" + FolderPath);
}else {
folder = new File(
Environment.getExternalStorageDirectory() + "/"
+ FolderPath);
}
if (!folder.exists())
folder.mkdirs();
String FilePath = folder.getAbsolutePath() + "/"
+ Path.substring(Path.lastIndexOf('/') + 1);
OutputStream output = new FileOutputStream(FilePath, false);
byte data[] = new byte[8192];
int count = -1;
while ((count = inputStream.read(data)) != -1) {
output.write(data, 0, count);
}
// flushing output
output.flush();
// closing streams
output.close();
inputStream.close();
}

Downloading a pdf generated by a plugin in a webview

I'm creating an app using Universal Android WebView App to access a webpage. This webpage has some downloadable pdfs, only available to logged in users.
The built in Download Manager doesn't work because the pdf is generated by a plugin, and sent in a http response.
I tried to implement the connection myself, tweaking this code http://www.codejava.net/java-se/networking/use-httpurlconnection-to-download-file-from-an-http-url
It works and the connection is established just fine, but the file is not downloaded because apparently the Content-Length received is -1. What could be the problem?
Here's the code:
public class HttpDownloadUtility extends AsyncTask<String, Integer, String> {
private static final int BUFFER_SIZE = 4096;
/**
* Downloads a file from a URL
* #param fileURL HTTP URL of the file to be downloaded
* #param saveDir path of the directory to save the file
* #throws IOException
*/
public String downloadFile(String fileURL, String saveDir) throws IOException {
String fileName = "";
URL url = new URL(fileURL);
HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
httpConn.setRequestProperty("Cookie", android.webkit.CookieManager.getInstance().getCookie("http://mywebsite.com"));
httpConn.connect();
int responseCode = httpConn.getResponseCode();
// always check HTTP response code first
if (responseCode == HttpURLConnection.HTTP_OK) {
String disposition = httpConn.getHeaderField("Content-Disposition");
String contentType = httpConn.getContentType();
int contentLength = httpConn.getContentLength();
if (disposition != null) {
// extracts file name from header field
int index = disposition.indexOf("filename=");
if (index > 0) {
fileName = disposition.substring(index + 10,
disposition.length() - 1);
}
} else {
// extracts file name from URL
fileName = fileURL.substring(fileURL.lastIndexOf("/") + 1,
fileURL.length());
}
System.out.println(url.toString());
System.out.println("Content-Type = " + contentType);
System.out.println("Content-Disposition = " + disposition);
System.out.println("Content-Length = " + contentLength);
System.out.println("fileName = " + fileName);
// opens input stream from the HTTP connection
InputStream inputStream = httpConn.getInputStream();
String saveFilePath = saveDir + File.separator + fileName;
// opens an output stream to save into file
FileOutputStream outputStream = new FileOutputStream(saveFilePath);
int bytesRead = -1;
byte[] buffer = new byte[BUFFER_SIZE];
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
outputStream.close();
inputStream.close();
System.out.println("File downloaded");
} else {
System.out.println("No file to download. Server replied HTTP code: " + responseCode);
}
httpConn.disconnect();
return fileName;
}
#Override
protected String doInBackground(String... url) {
String downloadedFile = "";
try{
downloadedFile = downloadFile(url[0], Environment.DIRECTORY_DOWNLOADS);
}catch(Exception e){
System.out.println(e.toString());
}
return downloadedFile;
}
}
I just found that the DownloadManager can be configured with the cookies I needed. Here's the code in case anyone needs it (I don't use the class I mentioned in the question anymore).
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, "mypdf.pdf");
request.allowScanningByMediaScanner();
request.setNotificationVisibility(1);
request.addRequestHeader("Cookie", CookieManager.getInstance().getCookie(url));
DownloadManager manager = (DownloadManager)getActivity().getSystemService(Context.DOWNLOAD_SERVICE);
manager.enqueue(request);

Application/octet-stream

I need to pass an image in application/octet-stream format. I think it means binary image data. How can I convert my drawable to this format?
Here is the code where I'll pass this data in the place of body :
StringEntity reqEntity = new StringEntity("{body}");
You can use HttpURLConnection, something like this:
Long BUFFER_SIZE = 4096;
String method = "POST";
String filePath = "FILE_NAME"
File uploadFile = new File(filePath);
if (!(uploadFile.isFile() && uploadFile.exists())) {
println 'File Not Found !!!!'
return;
}
URL url = new URL("http://your_url_here/" + uploadFile.name);
HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
String contentType = "application/octet-stream"
httpConn.setDoOutput(true);
httpConn.setRequestMethod(method);
httpConn.setRequestProperty("Accept", "*/*");
httpConn.setRequestProperty("Content-type", contentType);
OutputStream outputStream = httpConn.getOutputStream();
FileInputStream inputStream = new FileInputStream(uploadFile);
byte[] buffer = new byte[BUFFER_SIZE];
int bytesRead = -1;
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
outputStream.close();
inputStream.close();
println "Response message : "+httpConn.getResponseMessage();

Android download pdf from URL

I am trying to download a pdf from a URL where the pdf is part of the response stream rather that attaching it as part of the response. Below is the code that I tried but there is not much luck because when the pdf gets corrupted because there is some html content written inside. Not sure where the problem is.
URL url = new URL(fileURL);
HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
int responseCode = httpConn.getResponseCode();
// always check HTTP response code first
System.out.println("resp: "+responseCode);
if (responseCode == HttpURLConnection.HTTP_OK) {
String fileName = "";
String disposition = httpConn.getHeaderField("Content-Disposition");
String contentType = httpConn.getContentType();
int contentLength = httpConn.getContentLength();
if (disposition != null) {
// extracts file name from header field
int index = disposition.indexOf("filename=");
if (index > 0) {
fileName = disposition.substring(index + 10,
disposition.length() - 1);
}
} else {
// extracts file name from URL
fileName = fileURL.substring(fileURL.lastIndexOf("/") + 1,
fileURL.length());
}
System.out.println("Content-Type = " + contentType);
System.out.println("Content-Disposition = " + disposition);
System.out.println("Content-Length = " + contentLength);
System.out.println("fileName = " + fileName);
// opens input stream from the HTTP connection
InputStream inputStream = httpConn.getInputStream();
String saveFilePath = saveDir + File.separator + fileName;
// opens an output stream to save into file
FileOutputStream outputStream = new FileOutputStream(saveFilePath);
int bytesRead = -1;
byte[] buffer = new byte[1024*1024];
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
outputStream.close();
inputStream.close();
System.out.println("File downloaded");
} else {
System.out.println("No file to download. Server replied HTTP code: " + responseCode);
}
httpConn.disconnect();
any help would be appreciated. Thank you.
I would use Apache's commons-io FileUtils.copyURLToFile(URL, java.io.File) to accomplish this task.
an example implementation would be:
File f = new File(Environment.getExternalStorageDirectory(), "foo.pdf");
URL url = new URL("https://foosite.com/files/foo.pdf");
FileUtils.copyURLToFile(new URL("http://foo"), f);
at this point, your File object will be ready for processing.
Reference:
http://commons.apache.org/proper/commons-io/apidocs/org/apache/commons/io/FileUtils.html

Android download even if does not exist

try {
URL url = new URL("http://URL/Dragonfly.db");
HttpURLConnection c = (HttpURLConnection) url.openConnection();
c.setRequestMethod("GET");
c.setDoOutput(true);
c.connect();
String[] path = url.getPath().split("/");
String _file = path[path.length - 1];
int lengthOfFile = c.getContentLength();
if(lengthOfFile > 0){ // Copy file if Length > 0
String PATH = db.DB_PATH; ;//Environment.getExternalStorageDirectory()+
Log.v("", "PATH: " + PATH);
File file = new File(PATH);
file.mkdirs();
String fileName = "Dragonfly.db";
File outputFile = new File(file , fileName);
FileOutputStream fos = new FileOutputStream(outputFile);
InputStream is = c.getInputStream();
byte[] buffer = new byte[1024];
int len1 = 0;
while ((len1 = is.read(buffer)) != -1) {
fos.write(buffer, 0, len1);
}
fos.close();
is.close();
}else{
TestAdapter mDbHelper = new TestAdapter(getBaseContext());
mDbHelper.createDatabase();
}
} catch (IOException e) {
e.printStackTrace();
}
I use this code to update database, downloading a new one. but if i dont have a file on server, it replace the database i have for a new empty one (0bytes).
How can i download the file just if it exist on server?
Try to do a status response check:
int responseCode = c.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
{
// update database replacing the old one with the new one
} else {
// continue to use old database
}

Categories

Resources