Some PHP sites use a page to act as a middle man for handling file downloads.
With a browser this works transparently. There seems to a be a slight pause while the php page processes the request.
However, attempting a download through Java using a URL or HttpURLConnection returns a plain html page. How could I get the file downloads working in the same way?
Edit: Here is an example link:
http://depot.eice.be/index.php?annee_g=jour&cours=poo
Edit: Here is some of the code I've been testing:
// This returns an HTML page
private void downloadURL(String theURL) {
URL url;
InputStream is = null;
DataInputStream dis;
String s;
StringBuffer sb = new StringBuffer();
try {
url = new URL(theURL);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.connect();
if (conn.getResponseCode()!=HttpURLConnection.HTTP_OK)
return;
InputStream in = conn.getInputStream();
ByteArrayOutputStream bos = new ByteArrayOutputStream();
int i;
while ((i = in.read()) != -1) {
bos.write(i);
}
byte[] b = bos.toByteArray();
FileOutputStream fos = new FileOutputStream( getNameFromUrl( theURL ) );
fos.write(b);
fos.close();
conn.disconnect();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// This will throw Exceptions if the URL isn't in the expected format
public String getNameFromUrl(String url) {
int slashIndex = url.lastIndexOf('/');
int dotIndex = url.lastIndexOf('.');
System.out.println("url:" + url + "," + slashIndex + "," + dotIndex);
if (dotIndex == -1) {
return url.substring(slashIndex + 1);
} else {
try {
return url.substring(slashIndex + 1, url.length());
} catch (StringIndexOutOfBoundsException e) {
return "";
}
}
}
Considering no other constrains, you can read the redirected URL from the HTTP header and connect to that URL directly from JAVA.
There is an API setting to follow redirects automatically – but it should be true by default. How do you access the URL?
See Java API docs...
I think I've found a solution using HttpUnit. The source of the framework is available if you wish to see how this is handled.
public void downloadURL(String url) throws IOException {
WebConversation wc = new WebConversation();
WebResponse indexResp = wc.getResource(new GetMethodWebRequest(url));
WebLink[] links = new WebLink[1];
try {
links = indexResp.getLinks();
} catch (SAXException ex) {
// Log
}
for (WebLink link : links) {
try {
link.click();
} catch (SAXException ex) {
// Log
}
WebResponse resp = wc.getCurrentPage();
String fileName = resp.getURL().getFile();
fileName = fileName.substring(fileName.lastIndexOf("/") + 1);
System.out.println("filename:" + fileName);
File file = new File(fileName);
BufferedInputStream bis = new BufferedInputStream(
resp.getInputStream());
BufferedOutputStream bos = new BufferedOutputStream(
new FileOutputStream(file.getName()));
int i;
while ((i = bis.read()) != -1) {
bos.write(i);
}
bis.close();
bos.close();
}
System.out.println("Done downloading.");
}
Related
I have express js server as API. I need to send POST request to that server and my website needs to download PDF file to the client computer.
Here is my express server code:
const pdf = await generatePDF(data.originURL, data.url, data.pageOrientation); //pdf generation
// send pdf to client
res.writeHead(200, {
'Content-Type': 'application/pdf',
'Content-Disposition': 'attachment; filename=file.pdf',
'Content-Length': pdf.length
});
res.end(pdf);
In my website I have commandButton which call the action for POST request;
What I'm a doing wrong, I'm not getting any downloaded file in my website?
Method for making POST request:
public void makeRequest() {
HttpURLConnection connection = null;
try {
String imageExportServer = "url....";
URL url = new URL(imageExportServer);
connection = (HttpURLConnection)url.openConnection();
Stopwatch stopwatch = Stopwatch.createStarted();
try {
connection.setDoOutput(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/json");
try (OutputStream stream = connection.getOutputStream()) {
JsonObject configJson = new JsonObject();
configJson.addProperty("originURL", "url");
configJson.addProperty("url", "url...");
configJson.addProperty("pageOrientation", "someText");
stream.write(Builder().create().toJson(configJson).getBytes());
}
int responseCode = connection.getResponseCode();
if (responseCode != 200) {
//log.warn("Error response: ", responseCode);
}
String fileName = "";
String disposition = connection.getHeaderField("Content-Disposition");
String contentType = connection.getContentType();
int contentLength = connection.getContentLength();
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 = connection.getInputStream();
// opens an output stream to save into file
FileOutputStream outputStream = new FileOutputStream("neki.pdf");
int bytesRead = -1;
byte[] buffer = new byte[contentLength];
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
outputStream.close();
inputStream.close();
FileOutputStream fos = new FileOutputStream("neki.pdf");
fos.write(buffer);
fos.close();
System.out.println("File downloaded");
}
} catch (IOException e) {
//log.warn(e.getMessage(), e);
} finally {
//log.info("Exporting chart of type '%s' took %sms.", "tyoe", stopwatch.elapsed(TimeUnit.MILLISECONDS));
}
} catch (IOException e) {
//log.warn(e.getMessage(), e);
} finally {
if (connection != null) {
try {
connection.disconnect();
} catch (Exception e) {
//log.warn(e.getMessage(), e);
}
}
}
}
I don't know why i get a null value when i call the GetPHPData() function. The "out" variable returns nothing (""). I make a Toast.makeTest and it returns empty string. Please help. This is my code:
public class PHPConnect extends Activity
{
String url = "http://122.2.8.226/MITBookstore/sqlconnect.php";
HttpURLConnection urlConnection = null;
String out = null;
public String GetPHPData()
{
try {
urlConnection = (HttpURLConnection) new URL(url).openConnection();
urlConnection.setConnectTimeout(5000);
urlConnection.setReadTimeout(10000);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try
{
BufferedReader in = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
out = readStream(in);
}
catch (Exception e)
{
Toast.makeText(getApplicationContext(),e.getMessage(),Toast.LENGTH_SHORT).show();
}
finally
{
urlConnection.disconnect();
return out;
}
}
private String readStream(BufferedReader is)
{
try
{
ByteArrayOutputStream bo = new ByteArrayOutputStream();
int i = is.read();
while(i != -1)
{
bo.write(i);
i = is.read();
}
return bo.toString();
} catch (IOException e)
{
return e.getMessage();
}
}
}
By the way, im running a wamp server and I port forwarded my router, on local host, the url works, but on remote connection, it won't return a string. You can try out the url, the result is: "This is the output:emil"
Can you please try below piece of code which is working for me, also add INTERNET permission in android manifest file. Still if it is not working then may be issue with server end then try to debug it.
URL url;
try {
url = new URL("myurl");
HttpURLConnection urlConnection = (HttpURLConnection) url
.openConnection();
InputStream in = urlConnection.getInputStream();
InputStreamReader isw = new InputStreamReader(in);
int data = isw.read();
while (data != -1) {
char current = (char) data;
data = isw.read();
System.out.print(current);
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
My download scenario is: when i click on download link on jsp it calls signed applet method with file's id, from applet I call server side method by passing that id. I can get that file at server side but I want to return/pass that file back to my applet function.
My question is how to return back or pass downloaded file to my applet?
Or How can I set a file to response object at server side that can be useful at applet?
My Signed Applet :
private static void downloadEncryptedFile(String uuid) throws HttpException, IOException {
String uri = "http://localhost:8080/encryptFileDownload.works?uuid="+uuid;
HttpClient client = new HttpClient();
PostMethod postMethod = new PostMethod(uri);
postMethod.setRequestHeader("Content-type", "text/xml; charset=ISO-8859-1");
client.executeMethod(postMethod);
postMethod.releaseConnection();
}
My Server side function:
#RequestMapping(value = "/encryptFileDownload/{uuid}.works", method = RequestMethod.POST)
public String downloadEncryptFile(#PathVariable("uuid") String uuid, HttpSession session, HttpServletResponse response) {
try {
if (StringUtils.isNotEmpty(uuid)) {
LOG.info("-----UUID----");
Node node = contentRetrieveService.getByNodeId(uuid);
Node resource = node.getNode("jcr:content");
response.setContentType("application/octet-stream");
response.setHeader("Content-Disposition", "attachment; filename=\"" + node.getName() + "\"");
InputStream in = resource.getProperty("jcr:data").getBinary().getStream();
ServletOutputStream outs = response.getOutputStream();
int i = 0;
while ((i = in.read()) != -1) {
outs.write(i);
}
outs.flush();
outs.close();
in.close();
LOG.info("File Downloaded");
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
I got the solution; I just wanted to pass a file id download it and return that file back to my applet, hence I have made changes in my code as:
My Applet:
try {
URL urlServlet = new URL("uri for your servlet");
URLConnection con = urlServlet.openConnection();
con.setDoInput(true);
con.setDoOutput(true);
con.setUseCaches(false);
con.setRequestProperty(
"Content-Type",
"application/x-java-serialized-object");
// send data to the servlet
OutputStream outstream = con.getOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(outstream);
oos.writeObject(uuid);
oos.flush();
oos.close();
// receive result from servlet
InputStream instr = con.getInputStream();
ObjectInputStream inputFromServlet = new ObjectInputStream(instr);
String name = con.getHeaderField("filename");
File fi = new File(name);
int i = 0;
while ((i = inputFromServlet.read()) != -1) {
System.out.println(inputFromServlet.readLine());
}
inputFromServlet.close();
instr.close();
} catch (Exception ex) {
ex.printStackTrace();
}
Server side Function just replace with this:
OutputStream outs = response.getOutputStream();
outputToApplet = new ObjectOutputStream(outs);
int i = 0;
while ((i = in.read()) != -1) {
outputToApplet.write(i);
}
I have java code for file download through ftp, after download the file, it goes to default path. The specified destination path is not having the downloaded file. Why? my code is,
public class ftpUpload1
{
public static void main(String a[]) throws IOException
{
ftpUpload1 obj = new ftpUpload1();
URL url1 = new URL("ftp://vbalamurugan:vbalamurugan#192.168.6.38/ddd.txt" );
File dest = new File("D:/rvenkatesan/Software/ddd.txt");
obj.ftpDownload(dest, url1);
public void ftpDownload(File destination,URL url) throws IOException
{
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
try
{
URLConnection urlc = url.openConnection();
bis = new BufferedInputStream( urlc.getInputStream() );
bos = new BufferedOutputStream( new
FileOutputStream(destination.getName() ) );
int i;
//read byte by byte until end of stream
while ((i = bis.read())!= -1)
{
// bos.write(i);
bos.write(i);
}
System.out.println("File Downloaded Successfully");
}
finally
{
if (bis != null)
try
{
bis.close();
}
catch (IOException ioe)
{
ioe.printStackTrace();
}
if (bos != null)
try
{
bos.close();
}
catch (IOException ioe)
{
ioe.printStackTrace();
}
}
}
}
}
The downloaded file "ddd.txt" not in the "D:/rvenktesan/Software". It is located in "D:rvenkatesan/JAVA PROJECTS". Why? guide me to store the file in specified path? Thanks in adcance.
You problem is FileOutputStream(destination.getName() ) );
change this to: FileOutputStream(destination.getAbsolutePath() ) );
getName wil return the filename "ddd.txt" only. I assume you are starting your app from D:/rvenkatesan/JAVA PROJECTS
I am writing a desktop app in Java to upload a file to a folder on IIS server using HTTP PUT.
URLConnection urlconnection=null;
try{
File file = new File("C:/test.txt");
URL url = new URL("http://192.168.5.27/Test/test.txt");
urlconnection = url.openConnection();
urlconnection.setDoOutput(true);
urlconnection.setDoInput(true);
if (urlconnection instanceof HttpURLConnection) {
try {
((HttpURLConnection)urlconnection).setRequestMethod("PUT");
((HttpURLConnection)urlconnection).setRequestProperty("Content-type", "text/html");
((HttpURLConnection)urlconnection).connect();
} catch (ProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
BufferedOutputStream bos = new BufferedOutputStream(urlconnection
.getOutputStream());
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(
file));
int i;
// read byte by byte until end of stream
while ((i = bis.read()) >0) {
bos.write(i);
}
System.out.println(((HttpURLConnection)urlconnection).getResponseMessage());
}
catch(Exception e)
{
e.printStackTrace();
}
try {
InputStream inputStream;
int responseCode=((HttpURLConnection)urlconnection).getResponseCode();
if ((responseCode>= 200) &&(responseCode<=202) ) {
inputStream = ((HttpURLConnection)urlconnection).getInputStream();
int j;
while ((j = inputStream.read()) >0) {
System.out.println(j);
}
} else {
inputStream = ((HttpURLConnection)urlconnection).getErrorStream();
}
((HttpURLConnection)urlconnection).disconnect();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
This program creates an empty file on the destination folder (Test). The contents are not written to the file.
What is wrong with this program?
After you complete the loop where you are writing the BufferedOutputStream, call bos.close(). That flushes the buffered data before closing the stream.
Possible bug: bis.read() can return a valid 0. You'll need to change the while condition to >= 0.