I'm trying to download an.APK on Android's Chrome from my Glassfish server, but all I got is a "zero kb" file.
On Windows(PC)'s Chrome and on Android's Firefox it works correctly.
I'm using the following code:
private void downloadAPK(HttpServletRequest request, HttpServletResponse response, PrintWriter out){
String file = "/usr/local/glassfish4/glassfish/domains/domain1/applications/foo/foo.apk";
FileInputStream inputStream = null;
try{
File downloadFile = new File(file);
inputStream = new FileInputStream(downloadFile);
response.setHeader("Content-Disposition","attachment;filename="+file.getName());
int c = 0;
while ((c = inputStream.read()) != -1)
out.write(c);
} catch (Exception e) {
// code
}
// closing code
}
There is something that I'm missing to make it work on Android's Chrome?
Related
This should be an easy learning task but something went wrong:
Use API request to get image from some link and check it is in Base64 standard.
private static void getRequest() throws IOException {
URL url = new URL("http://apimeme.com/meme?meme=Alarm-Clock&top=Top+text&bottom=Bottom+text");
InputStream is = (InputStream) url.openStream();
FileInputStream imageInFile = new FileInputStream(is.toString());
byte imageData[] = new byte[2048];
imageInFile.read(imageData);
System.out.println(isBase64(imageInFile.toString()));
}
static boolean isBase64(String path) {
try {
Base64.getDecoder().decode(path);
return true;
} catch(IllegalArgumentException e) {
return false;
}
}
Right now problem is on line
InputStream is = (InputStream) url.openStream();
Server sends 403. How to fix this? Method isBase64 should work but the program doesn't reach this line.
Your need 3 header for avoid http 403 error code
private static void getRequest() throws IOException {
URL url = new URL("http://apimeme.com/meme?meme=Alarm-Clock&top=Top+text&bottom=Bottom+text");
URLConnection is = url.openConnection();
is.setRequestProperty("Host", "apimeme.com");
is.setRequestProperty("Cookie", "*");
is.setRequestProperty("User-Agent", "*");
byte[] imageData = new byte[2048];
File downloadFile = new File("download.png");
FileOutputStream outputStream = new FileOutputStream(downloadFile);
int read;
while ((read = is.getInputStream().read(imageData)) != -1) {
outputStream.write(imageData, 0, read);
}
outputStream.close();
System.out.println(isBase64(downloadFile.getAbsolutePath()));
}
403 is means that you do not have permission to view this URL. You cannot do anything to fix this client side, even authorization would not help (if the ressource required authorization, the server would send 401 instead). So to fix the issue, whoever is in charge of the web server delivering the URL you're trying to access will have to fix this - if they think you should have access.
I have a URL i.e http://downloadplugins.verify.com/Windows/SubAngle.exe .
If I paste it on the tab and press enter then the file (SubAngle.exe) is getting downloaded and saved in the download folder. This is a manual process. But it can be done with java code.
I wrote the code for getting the absolute path with the help of the file name i.e SubAngle.exe.
Requirement:- With the help of the URL file gets downloaded,Verify the file has been downloaded and returns the absolute path of the file.
where locfile is "http://downloadplugins.verify.com/Windows/SubAngle.exe"
public String downloadAndVerifyFile(String locfile) {
File fileLocation = new File(locfile);
File fileLocation1 = new File(fileLocation.getName());
String fileLocationPath = null;
if(fileLocation.exists()){
fileLocationPath = fileLocation1.getAbsolutePath();
}
else{
throw new FileNotFoundException("File with name "+locFile+" may not exits at the location");
}
return fileLocationPath;
}
easy and general function that im using:
import org.apache.commons.io.FileUtils;
public static void downLoadFile(String fromFile, String toFile) throws MalformedURLException, IOException {
try {
FileUtils.copyURLToFile(new URL(fromFile), new File(toFile), 60000, 60000);
} catch (FileNotFoundException e) {
e.printStackTrace();
System.out.println("exception on: downLoadFile() function: " + e.getMessage());
}
}
Instead of writing this huge code, go for Apache's commons.io
Try this:
URL ipURL = new URL("inputURL");
File opFile = new File("outputFile");
FileUtils.copyURLToFile(ipURL, opFile);
Code to DownloadFile from URL
import java.net.*;
import java.io.*;
public class DownloadFile {
public static void main(String[] args) throws IOException {
InputStream in = null;
FileOutputStream out = null;
try {
// URL("http://downloadplugins.verify.com/Windows/SubAngle.exe");
System.out.println("Starting download");
long t1 = System.currentTimeMillis();
URL url = new URL(args[0]);
// Open the input and out files for the streams
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
in = conn.getInputStream();
out = new FileOutputStream("YourFile.exe");
// Read data into buffer and then write to the output file
byte[] buffer = new byte[8192];
int bytesRead;
while ((bytesRead = in.read(buffer)) != -1) {
out.write(buffer, 0, bytesRead);
}
long t2 = System.currentTimeMillis();
System.out.println("Time for download & save file in millis:"+(t2-t1));
} catch (Exception e) {
// Display or throw the error
System.out.println("Erorr while execting the program: "
+ e.getMessage());
} finally {
// Close the resources correctly
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
}
}
}
Configure the value of fileName properly to know where the file is getting stored.
Source: http://www.devmanuals.com/tutorials/java/corejava/files/java-read-large-file-efficiently.html
The source was modified to replace local file with http URL
Output:
java DownloadFile http://download.springsource.com/release/TOOLS/update/3.7.1.RELEASE/e4.5/springsource-tool-suite-3.7.1.RELEASE-e4.5.1-updatesite.zip
Starting download
Time for download & save file in millis:100184
i write simple applet to download file from HTTP URL.
In Eclipse or Netbeans, it 's work well and can download file to d://abc//123.iso on my HDD.
This is my code :
public class download {
public static void saveUrl(final String filename, final String urlString)
throws MalformedURLException, IOException {
BufferedInputStream in = null;
FileOutputStream fout = null;
try {
in = new BufferedInputStream(new URL(urlString).openStream());
fout = new FileOutputStream(filename,true);
final byte data[] = new byte[1024];
int count;
fout.write(data, 0, count);
} finally {
if (in != null) {
in.close();
}
if (fout != null) {
fout.close();
}
}
}
}
public class HelloWorldApplet extends Applet
{
public void paint (Graphics g)
{
g.drawString ("Download file", 25, 50);
String url ="http://downloads.asterisk.org/pub/telephony/asterisk-now/AsteriskNOW-612-current-32.iso";
String file_out = "d:\\abc\\123.iso";
download.saveUrl(file_out, url);
}
}
==========================
But when export to jar file and run with html, browser can creat new file 123.iso on my HDD but the size of this file is always 2 Kbps. i think it do not download anything.
Please help me
Thanks so much
P/s : i try to sign jar file with jarsigner but it does not solve the problem
Although I'm skeptical as to the code above doing anything at all as posted, if even compiling, here's the solution I use for doing automatic update downloads of large (>100 MB) files:
HttpGet httpGet;
RequestConfig requestConfig;
getProxySettings();
//Check to see if there is a proxy availabble.
if (!LicensePreloader.proxyAddr.equals("")) {
requestConfig = RequestConfig.custom()
.setSocketTimeout(5000)
.setConnectTimeout(5000)
.setConnectionRequestTimeout(5000)
.setProxy(new HttpHost(LicensePreloader.proxyAddr, LicensePreloader.proxyPort))
.build();
} else {
//No proxy was available, just use regular internet.
requestConfig = RequestConfig.custom()
.setSocketTimeout(5000)
.setConnectTimeout(5000)
.setConnectionRequestTimeout(5000)
.build();
}
httpGet = new HttpGet(this.remoteUrl);
HttpResponse response;
InputStream remoteContentStream = null;
OutputStream localFileStream = null;
try {
httpGet.setConfig(requestConfig);
response = httpClient.execute(httpGet);
//This builds the content of our file we're downloading.
remoteContentStream = response.getEntity().getContent();
long fileSize = response.getEntity().getContentLength();
File dir = localFile.getParentFile();
dir.mkdirs();
localFileStream = new FileOutputStream(localFile);
//Set the buffer, in our use case, it's always the deafult 8192 bytes.
byte[] buffer = new byte[bufferSize];
int sizeOfChunk;
int amountComplete = 0;
//Simply loop through and download the file in 'chunks'
while ((sizeOfChunk = remoteContentStream.read(buffer)) != -1) {
localFileStream.write(buffer, 0, sizeOfChunk);
amountComplete += sizeOfChunk;
updateProgress(amountComplete, fileSize);
}
return localFile;
} finally {
//Make sure to clean everything up.
try {
if (remoteContentStream != null) {
remoteContentStream.close();
}
if (localFileStream != null) {
localFileStream.close();
}
} catch (IOException ex) {
//If we're here, it's likely because the internet conneciton
//couldn't be established, or it was cut short in the middle.
ex.printStackTrace(System.out);
failed();
}
}
}
This is obviously overkill for your application, and you can probably just forget all the proxy business, but I kept it in there for completeness sake. There are a couple helper methods I didn't include, but again, they're almost all exclusively for proxy handling.
good luck!
You are writing one the first read in the input. You need to write the file until the input is empty.
Try this while in you code
while ((count = in.read(data)) != -1) {
fout.write(data, 0, count);
...
}
I am using the following code to download a file within the WEB-INF
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
String b = null;
Cookie[] cookies = request.getCookies();
if (cookies != null) {
for (Cookie cookie : cookies) {
if (cookie.getName().equals("thecookie")) {
b = cookie.getValue();
}
}
}
BufferedReader br = new BufferedReader(new FileReader(b+"/logs.txt"));
String path = br.readLine();
br.close();
File file = new File(path+"/Results.xlsx");
FileInputStream fileIn = new FileInputStream(file);
ServletOutputStream out = response.getOutputStream();
response.setHeader("Content-Disposition", "attachment; filename=Result.xlsx");
response.setContentType(
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
byte[] outputByte = new byte[4096];
int bytesRead;
//copy binary contect to output stream
while((bytesRead = fileIn.read(outputByte)) != -1)
{
out.write(outputByte, 0, bytesRead);
}
fileIn.close();
out.flush();
out.close();
}
along with this I want to download another file at the same location Results.csv I've tried using the same code above twice but it didn't work.
How to download multiple files without using zipoutputstream?
MIME/multipart responses are, as far as I know, not part of the HTTP standard. Some browsers seem to support it, but I recommend against using it.
Instead, you could pack those files into a ZIP file (using a ZipOutputStream), and return that as your response. That's also the way DropBox handles the download of multiple files at once.
It is possible but having them in separate requests if you plan to work within every browser.
Here a sample script for downloading a file via javascript
function downloadFile(url, name) {
var link = document.createElement("a");
link.download = name;
link.href = url;
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
delete link;
}
downloadFile(url1,filenam1);
downloadFile(url2,filenam2);
downloadFile(url3,filenam3);
...
I am working on an applet that records voice and uploads to a servlet.
Here is the code of the upload thread in the applet
class uploadThread extends Thread {
#Override
public void run() {
try {
//Preparing the file to send
AudioFileFormat.Type fileType = AudioFileFormat.Type.WAVE;
File file = File.createTempFile("uploded", ".wav");
byte audio[] = out.toByteArray();
InputStream input = new ByteArrayInputStream(audio);
final AudioFormat format = getFormat();
final AudioInputStream ais = new AudioInputStream(input, format, audio.length / format.getFrameSize());
AudioSystem.write(ais, fileType, file);
//uploading to servlet
FileInputStream in = new FileInputStream(fileToSend);
byte[] buf = new byte[1024];
int bytesread = 0;
String toservlet = "http://localhost:8080/Servlet/upload";
URL servleturl = new URL(toservlet);
URLConnection servletconnection = servleturl.openConnection();
servletconnection.setDoInput(true);
servletconnection.setDoOutput(true);
servletconnection.setUseCaches(false);
servletconnection.setDefaultUseCaches(false);
DataOutputStream out = new DataOutputStream(servletconnection.getOutputStream());
while ((bytesread = in.read(buf)) > -1) {
out.write(buf, 0, bytesread);
}
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
System.err.println("Error during upload");
}
}
}//End of inner class uploadThread
Here is the code of the grab file method in the servlet:
java.io.DataInputStream dis = null;
try {
int fileLength = Integer.valueOf(request.getParameter("fileLength"));
String fileName = request.getParameter("fileName");
dis = new java.io.DataInputStream(request.getInputStream());
byte[] buffer = new byte[fileLength];
dis.readFully(buffer);
dis.close();
File cibleServeur = new File("/Users/nebrass/Desktop/" + fileName);
FileOutputStream fos = new FileOutputStream(cibleServeur);
fos.write(buffer);
fos.close();
} catch (IOException ex) {
Logger.getLogger(UploadServlet.class.getName()).log(Level.SEVERE, null, ex);
} finally {
try {
dis.close();
} catch (Exception ex) {
Logger.getLogger(UploadServlet.class.getName()).log(Level.SEVERE, null, ex);
}
}
I have created a certificate with the keytool. And i have signed the JAR of the applet.
I have added the applet to the jsp file and it is working, and have the all permissions (I tried to save a file on a desktop using the applet)
Update: The problem is that the file is not sent, and when i try to debug the servlet, it is not invoked by the the applet.
Please help
That's not how it works. You've just opened a URLConnection and wrote to the output stream. That way you're assuming something like a socket connection, but here we need more of a HttpUrlConnection and then a request-parameter and a multi-part request.
Google Search
Google found lots of solutions, but for the completeness of the answer, I'm adding one below :
https://stackoverflow.com/a/11826317/566092
You want up upload a file from the server to the user desktop?
I doubt this will be allowed, for obvious security reasons.
Why don't you just call the servlet directly from the browser? And "save as" the file?
Here is an exemple on how to send a file (any type) from a servlet.
protected void doPost(
...
response.setContentType("your type "); // example: image/jpeg, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/octet-stream
response.setHeader("Content-Disposition","attachment; filename=\"your_filename\"");
File uploadedFile = new File("/your_file_folde/your_file_name");
if (uploadedFile.exists()){
FileUtils.copyFile(uploadedFile, response.getOutputStream());
}
else { // Error message
}
....
}