Problems in Downloading a file from a web site using HttpClient

Hi,
My requirement is to download a file from a website using a java program. I have written a program using HttpClient API but I am unable to do so. Reality is that I don't know how to proceed with the HttpClient API to get the file downloaded. Same file can also be downloaded manually by login to that website, below mentioned steps are to be followed to download the file manually.
1. Login to the website using Login/Password (I have valid login/password)
2. Two options (links) are there (a) Report (b) Search [I am chosing report option]
3. Newly opened window shows two tabs (a) Today (b) From & To [I am selection Today tab]
4. Every tab has two radio button (a) File (b) Destination [Destination is selected by me]
5. When Search button is pressed. A link gets created when that link is clicked file download popup is opened which allows facility to open/save the file.
All these 5 step are to be followed in a java program to download the file. Please help in doing the same.

// first URL which is used to open the website, this will have two text fields userName and password
String finalURL = "http://www.xyz.in/mstatus/index.php";
SMSGatewayComponentImpl obj = new SMSGatewayComponentImpl();
obj.sendMessage(finalURL);
public void sendMessage(String finalURL) {
String ipAddrs = "a.b.c.d";
int port = 8080;
boolean flag = false;
try {
// Create an instance of HttpClient.
HttpClient client = new HttpClient();
HostConfiguration hostConfig = new HostConfiguration();
hostConfig.setProxy(ipAddrs,port);
client.setHostConfiguration(hostConfig);
// Create a method instance.
String cookieName=null;
String cookieValue=null;
// Here URL for the login page is passed and passing the user/password
PostMethod method = new PostMethod(finalURL);
method.setRequestHeader("userid","userName");
method.setRequestHeader("passwd","pwd");
// Execute the method.
int statusCode = client.executeMethod(method);
Cookie[] cookies = client.getState().getCookies();
for (int i = 0; i < cookies.length; i++) {
Cookie cookie = cookies;
cookieName = cookie.getName();
cookieValue = cookie.getValue();
System.err.println(
"Cookie: " + cookie.getName() +
", Value: " + cookie.getValue() +
", IsPersistent?: " + cookie.isPersistent() +
", Expiry Date: " + cookie.getExpiryDate() +
", Comment: " + cookie.getComment());
NameValuePair[] respParameters = method.getResponseHeaders();
String cookie = "";
for(NameValuePair o : respParameters){
     System.out.println("Name : "+o.getName());
     System.out.println("Value : "+o.getValue());
     if("Set-Cookie".equalsIgnoreCase(o.getName()))
          cookie = o.getValue();
NameValuePair[] footParameters = method.getResponseFooters();
System.out.println("****************** Footer Values *******************");
for(NameValuePair o1 : footParameters){
System.out.println("Name : "+o1.getName());
System.out.println("Value : "+o1.getValue());
// This is jthe URL which comes when login/passowrd is entered and Login button is pressed.
// I am trying to get the cookie from the first URL and pass this cookie for the second URL so that the session can be maintained
// Here I may be wron..don't know is this the right way to download the file like this.....????
finalURL = "http://www.xyz.in/mstatus/mainmenugrsms.php";
     method = new PostMethod(finalURL);
     method.setRequestHeader(cookieName,cookieValue);
     method.setRequestHeader("userid","userName");
     method.setRequestHeader("passwd","pwd");
     method.setRequestHeader("Set-Cookie",cookie);
     statusCode = client.executeMethod(method);
     respParameters = method.getResponseHeaders();
for(NameValuePair o : respParameters){
System.out.println("Name : "+o.getName());
     System.out.println("Value : "+o.getValue());
// and this is the final URL which i got when that final link which enabled file download from the website have been copied as a shortcut and
// pasted in a notepad. I was thinking that this will return the file as an input stream. but its not happening.
     finalURL = "http://www.xyz.in/mstatus/dlr_date.php#";
     method = new PostMethod(finalURL);
     method.setRequestHeader("Set-Cookie",cookie);
     method.setRequestHeader("userid","userName");
// userid and passwd field are obtained when login/password page contents are seen using view source of that html
     method.setRequestHeader("type","1");
     // trying to set the cookie so that session can be maintained
method.setRequestHeader(cookieName,cookieValue);
     method.setRequestHeader("passwd","pwd");
     statusCode = client.executeMethod(method);
     ObjectInputStream objRetInpuStream = new ObjectInputStream(method.getResponseBodyAsStream());
     System.out.println("objRetInpuStream : "+objRetInpuStream);
     if(objRetInpuStream!=null)
     System.out.println("objRetInpuStream available bytes : "+objRetInpuStream.available());
     String returnFile=(String)objRetInpuStream.readObject();
     System.out.println("Returned value \n : "+returnFile);
     respParameters = method.getResponseHeaders();
     for(NameValuePair o : respParameters){
     byte[] responseBody = method.getResponseBody();
     System.out.println("Response Body : "+new String(responseBody));
     if (statusCode != HttpStatus.SC_OK) {
          System.out.println("Error: " + method.getStatusLine());
     } else {
          System.out.println(method.getStatusLine());     
     } catch(Exception nfe) {
               System.out.println("Exception " + nfe);
Output
=====
/home/loguser/batch> sh run.sh SMSGatewayComponentImpl
Classname : SMSGatewayComponentImpl
run.sh[4]: test: 0403-004 Specify a parameter with this command.
final URL : http://www.xyz.in/mstatus/index.php
client is :org.apache.commons.httpclient.HttpClient@190e190e
Cookie: PHPSESSID, Value: anqapu83ktgp8hlot06jtbmdf1, IsPersistent?: false, Expiry Date: null, Comment: null
Name : Date
Value : Thu, 06 May 2010 09:08:47 GMT
Name : Server
Value : Apache/2.2.3 (Red Hat)
Name : X-Powered-By
Value : PHP/5.1.6
Name : Set-Cookie
Value : PHPSESSID=anqapu83ktgp8hlot06jtbmdf1; path=/
Name : Expires
Value : Thu, 19 Nov 1981 08:52:00 GMT
Name : Cache-Control
Value : no-store, no-cache, must-revalidate, post-check=0, pre-check=0
Name : Pragma
Value : no-cache
Name : Content-Length
Value : 4792
Name : Content-Type
Value : text/html; charset=UTF-8
Name : X-Cache
Value : MISS from dcp.pas.abc.in
Name : X-Cache-Lookup
Value : MISS from dcp.pas.abc.in:8080
Name : Via
Value : 1.0 dcp.pas.abc.in:8080 (squid/2.6.STABLE21)
Name : Proxy-Connection
Value : keep-alive
Cookie Value : PHPSESSID=anqapu83ktgp8hlot06jtbmdf1; path=/
****************** Footer Values *******************
Name-2 : Date
Value-2: Thu, 06 May 2010 09:08:47 GMT
Name-2 : Server
Value-2: Apache/2.2.3 (Red Hat)
Name-2 : X-Powered-By
Value-2: PHP/5.1.6
Name-2 : Expires
Value-2: Thu, 19 Nov 1981 08:52:00 GMT
Name-2 : Last-Modified
Value-2: Thu, 06 May 2010 09:08:47 GMT
Name-2 : Cache-Control
Value-2: no-store, no-cache, must-revalidate, post-check=0, pre-check=0
Name-2 : Pragma
Value-2: no-cache
Name-2 : Location
Value-2: index.php
Name-2 : Content-Length
Value-2: 0
Name-2 : Content-Type
Value-2: text/html; charset=UTF-8
Name-2 : X-Cache
Value-2: MISS from dcp.pas.abc.in
Name-2 : X-Cache-Lookup
Value-2: MISS from dcp.pas.abc.in:8080
Name-2 : Via
Value-2: 1.0 dcp.pas.abc.in:8080 (squid/2.6.STABLE21)
Name-2 : Proxy-Connection
Value-2: keep-alive
Cookie Value second time : PHPSESSID=anqapu83ktgp8hlot06jtbmdf1; path=/
**Exception java.io.EOFException**
Is my approach to download the file fromthe website ok????? please help me.

Similar Messages

  • Downloading PDF files from reliable web-sites U-R-G-E-N-T

    Hi,
    Since last year I encounter regular (close to 100%) problems downloading PDF files from reliable web-sites (for sure web-sites from which I could troubleless download PDF files in the past) The result on my HDD : 0KB pdf file ! = An empty file
    This is very anoying and I am sure I am not the only one who encounters this.
    Please review your procedures and make this possible again.
    Note: I uninstalled Adobe Reader, reset Safari, closed Safari, re-installed Adobe Reader : no results !
    THANKS FOR HELPING ASAP !
    I travel a lot and have to bring my files with me as internet is not always available in the countries where I work
    Christian

    Hi Christian,
    I've had problems for ages with this but I did notice that after I went through the reinstall with Apple yesterday I now have a couple of different options that are working.
    Yesteday I uninstalled reader, restarted my computer and then reinstalled again. I didn't think it had worked for me but after some extra experimentation I have discovered a couple of things.
    On some websites eg: https://www.gatewaycu.com.au/uploadedFiles/PDF/Forms/Quick%20Debit%20Authority.pdf
    it is coming up with a toolbar (I suppose it's called) at the top of the PDF and it is allowing me to print and save to my desktop, open the pdf and print YEAH.
    Also with another website the PDF is showing up differently. eg http://media.wix.com/ugd/99e891_6110f024d956431abb7b66dd24f19251.pdf
    This shows up like it used to but the difference is that if you try to save as or print throught the safari options like I used too it doesn't work, BUT if you hover down the bottom of the PDF it brings up a bar type box (sorry I don't know the technical word for this) then you can print, save to desktop, documents etc and then print from there too.
    YEAH! It looks like (I hope) that the problem is solved. You have to go about it in a couple of different ways depending on the website, but hey, I don't think that's so bad as long as I can actually print my PDF's. It's better that not being able to access any of them which is what's been happening for the last few months.
    I hope this helps you guys out and if you have any problems just let me know and I'll try and explain it better for you.
    Cheers
    Andrea

  • Cannot view or download PDF files from secure web site with Reader X.

    Ran into a similar problem when Reader X first came out (Reader 9 had been working fine).  Only a blank window was displayed, but a work around was to "Save As" and use the view option to display and print the document. I recently had to replace my modem. Since then, that work around option is no longer available; it errors out saying that the file could not be downloaded.  We are using IE9 and Windows 7.  I tried another browser, Google Chrome, with the same negative results. Also, I got the same results on another secure website.  I have deleted and downloaded another copy of Reader X (10.1.1) and checked for updates, run the Repair program, and confirmed that Protected Mode and AdobePDF.dll are both enabled.  I looked at my Internet settings, too but found nothig that would obviously
    interfere with Reader.

    Usually, this message occurs with Windows. First time I've seen it with OS X. Looking into it.

  • Download a file from the web

    Helo,
    I have to download a file from the web and copy it to the file system (ex: download from http://172.26.20.22/test.csv to \\server01\teste.csv).
    I must do this using only pl/sql and java sources, I have to do this calling a procedure from pl/sql and the server doesn't have any component installed.
    I've built a java procedure using java to download the file, but it give-me AccessControlException when trying to download.
    Can anyone tel me what permissions I should have to accomplish this? Is there any other easier way?
    Thanks.

    Thanks a lot! Your post was very helpfull.
    I create a procedure do download the file from the web and record in a network share.
    But I'm still having a problem while writing that each line in my source file generate a duplicate line in my destination one.
    Can you help me with that problem to?
    Thanks
    My procedure is below:
    create or replace procedure SP_DOWNLOAD(astr_url_orig varchar2, astr_cam_dest varchar2, astr_nome_arq_dest varchar2) is
    l_pagina utl_http.html_pieces;
    l_arquivo utl_file.file_type;
    begin
    l_pagina := utl_http.request_pieces(astr_url_orig);
    l_arquivo := utl_file.fopen(astr_cam_dest, astr_nome_arq_dest, 'W');
    for i in 1 .. l_pagina.count
    loop
    utl_file.put_nchar(l_arquivo, l_pagina(i));
    dbms_output.put_line(l_pagina(i));
    end loop;
    utl_file.fclose(l_arquivo);
    end SP_DOWNLOAD;

  • When i download a file from the web i get "Anti-Virus Program not found " message. This has been happening since I change anti-virus programs for CA etrust to Sophos. How do I get Firefox to recognise my new Anti-virus program?

    every time i download a file from the web (ie. a PDF file) i get "Anti-Virus Program not found " message. This has been happening since I changed anti-virus programs for CA etrust to Sophos. How do I get Firefox to recognise my new Anti-virus program?

    That is a very good warning provided by the Download Statusbar extension. Something like that should been built into Firefox. I filed this Bug report a couple of years ago, about the lack of a warning like that. <br />
    https://bugzilla.mozilla.org/show_bug.cgi?id=480855 <br />
    I have looked everywhere that I can think of to find a list of '''IOfficeAntiVirus providers''' ''(as mentioned in the Bug report)'' that will work with Firefox, so I can't answer that for you.
    You might want to ask the developer of the Download Statusbar extension about it. He might know which AV programs are compatible with the Windows API that Firefox uses for the download scan. <br />
    http://dlstatusbar.proboards.com/index.cgi? <br />

  • I'm unable to print pdf files from certain web sites. I have just changed to Mavericks

    i'm unable to print pdf file from certain web site. I just changed over to Mavericks.

    You will need to access that PDF on your computer first, before you can print it — unless that PDF is corrupted, which occasionally happens. Your printer needs to be configured and working.
    Default PDF web-browser plug-in in Safari, latest (Firefox/Chrome) also built-in.
    Click on the remote PDF link to open in browser
    On Mavericks, you will need to click through security challenges for the PDF
    File menu > Print
    Right-click on remote PDF file and then choose Download Linked File As...Open that file in /Applications/Preview.appFile > print
    Adobe Reader 11.0.04 PDF plug-in
    Same security challenges on Mavericks as first bullet
    With PDF imaged in browser, either select print icon from the plug-in toolbar, or mouse over the bottom one inch of displayed document and you will see a printer icon in the popup toolbar. Use that.

  • I can't download ARW files from the card I use in my SONY RX100M2

    I can't download ARW files from the card I use in my SONY RX100M2

    You could just download and install LR5.2 right now
    Mac: http://www.adobe.com/support/downloads/detail.jsp?ftpID=5647
    Win: http://www.adobe.com/support/downloads/detail.jsp?ftpID=5648
    Enter your serial number (when you receive it) to license the software on your computer.

  • Bug:Downloading pdf file from the web,file name in dialog box populates with incorrect file name

    Hi Gurus
    When downloading any pdf file from the web using adobe Reader X the file name dialog box populates with incorrect file name
    compared to the saved file name of the document downloaded.
    Clarity
    1. Download any pdf file from the web
    2. Click File, Save as note the populated File Name
    3. Compare the populated file name with the saved file name of the documant yuo are downloading.
    4. The file Name is incorrect...
    Is there any work around on this issue?Can someone please help?..
    OS:Windows7
    Reader: Adobe Reader X
    I've tried a couple of other versions and still get the same results...

    Are you downloading the file (right-click, save link as), or just opening it by clicking it?
    If the latter, then what happens is the file is loaded to the temporary internet files folder by IE and assigned a temporary name, which is then used when you're trying to save it.
    You can test this out by going to File - Document Properties before trying to save and looking at the file's location.

  • Problems with downloading music files from particular websites

    Has anyone else had problems using the Calabash or Afropop websites to download music files? I am able to download using Tiger on my MacBook Pro but each time I try the same with Leopard on my iMac, I get a message that the file does not exist. However, I am able to download music files from other sites like Music for Robots so I am not sure if there is something wrong with the sites themselves?

    The files are definitely corrupted because they skip and have areas that sound like the file bits are jumbled.  I verified this on two different computers.  Dragging the same song straight from the server to the computer or streaming it the songs
    play fine.  I also had trouble with the same hard drives corrupting music and pictures when I had the raid tower in Raid 0.  I have since put the drives in clean mode and reformatted full to NTFS.  The Raid tower is a TR4UTBPN with two WD 1.5tb
    7200 drives.  I am running them in USB 3.0 mode with supplied turbo USB software to super speed the tower.  My pictures when they corrupt have solid color banding all through the middle.  I may try making a folder on one of the internal server
    drives and try downloading and see if they are corrupt as well.  when I say it corrupted the files before I mean you couldn't stream them copy them or look at them on the server without them being corrupted.  Any thoughts?

  • Download IDOC structure from SAP web Site

    HI
    to anticipate the SAP ERp upgrade, i would like to download the most up to date Idoc structure (for ADRMAS and DEBMAS) . Instead of download this structure from an SAP Instance , i would like to download it from SAP Web site.
    Does anybody already do that ?
    How can i proceed
    regards
    fred

    Hi Siva
    Thanks for your input. I Know and i did that from a couple of years , neverthelss, each time you upgarde your system, you have to rewrite your development. My goal is to try to anticipate that by for exemple download the IDOC structure in advance . Let me say IDOC structure used by MySAP ERp 2007 instaed of SAP ERP 4.6. If i can download those STructure i will not be obliged to rewrite my Dev after each upgrade. Do you see what i mean ?
    regards
    fred

  • Why do pdf files from some web sites download as aspx files, which I can't open from Firefox but I can in Internet Explorer?

    I have tried downloading files which are supposed to be pdf but they download as aspx files. This doesn't happen if I use Internet Explorer and other pdfs from the same web site download without a problem.

    To make a long story short, the server can send a preferred file name but isn't always programmed to do so. IE sniffs the beginning of the file and may override what is sent by the server; Firefox does not.
    You can manually change the file extension when you save it (if you have Firefox set to ask you where to save) or you can rename it after it is saved.

  • Downloading a file from the web

    Hi,
    I'm trying to implement an automatic update feature in one of my applications. This is done by downloading a jar from from my web server. I've written this method to download the file, but the file it downloads it says isn't a valid archive - so there's something wrong with my download method, but I don't know what. Any ideas on what's wrong with this method? Or any other ideas on how to download the file? I don't want to use FTP as I don't want to include my username / password in the application code.
        public static void getRemoteFile(String fileName) {
            try {
                FileWriter out = new FileWriter( "new.jar", true );
                URL url = new URL(fileName);
                URLConnection ex = url.openConnection();
                BufferedReader in = new BufferedReader( new InputStreamReader( ex.getInputStream() ) );
                String inputLine = "";
                while ( ( inputLine = in.readLine() ) != null ) {
                    out.write( inputLine );
                out.close();
                in.close();
            } catch( Exception e ) {
                // do nothing
        } // end the main method

    Thanks for the replies. I created this method instead, but I keep getting this error:
    java.lang.IllegalArgumentException: URI scheme is not "file"
    Any ideas what this means?
                File file = new File( new URI("http://www.mydomain.com/test.jar") );
                InputStream fis = new FileInputStream(file); // copy target
                OutputStream fos = new FileOutputStream("new.jar"); // copy destination
                int nSize = fis.available();
                byte [] puffer = new byte[nSize];
                fis.read( puffer, 0, nSize );
                fos.write( puffer, 0, puffer.length );
                fis.close();
                fos.close();

  • How to download a file from the web

    Say, a PDF.

    Hi!
    Your question is marked as a Firefox OS question which is Mozilla's own mobile operating system. Thanks for contacting Mozilla Support!
    It seems that PDFs cannot be downloaded from the web at this moment, however there are apps from the marketplace you can download to open already downloaded PDFs available on your microSD card.

  • Cannot Download Files from Certain Web Site

    There is a website I must use for work quite often. Whenever I try to download or open a file from the site, I get the following error:
    Safari can't open the file.
    Safari can't open the file ""2010 Pennsylvania Release Notes.pdf" because ""2010 Pennsylvania Release Notes.pdf" has moved since you downloaded it.
    I am using a Windows XP machine and these files work fine with any other browser. I really want to make Safari my default browser, but it is out of the question as long as this continues to happen with Safari alone.

    I just noticed, when I try downloading a PDF file using Safari from this website, it puts a " in front of the file name. It does not do this with any other browser. I think this may be what is causing the issue. Does anyone know how to fix this? Thanks!!

  • Getting Server Busy window when trying to download a .pdf file from any web site.

    When the "Server Busy" window opens, there are 3 choices: switch to; retry; cancel. I select switch to; it starts downloading the file, but appears to be stuck/locked up at a certain point. I usually have to go to Task Manager and cancel the download. Sometimes, after trying different things, the .pdf succeeds in downloading' can't tell what does/doesn't work. Retry doesn't do anything. Cancel doesn't close the Server Busy window.

    See: http://helpx.adobe.com/x-productkb/policy-pricing/configuration-error-cs5.html

Maybe you are looking for

  • Send paypal subscription amount to new recipient instead of old recipient

    We need to create web app, we want paypal account holder to authorize web app to send money from paypay holder account on behalf of paypal account holder. Using this way how we can send subscription amount to new recipient instead of old one. Because

  • Help with downloading After Effects

    Although I have a subscription to creative cloud student and teacher edition I am unable to download After Effects, please advise!

  • Sun Application Server8

    Im getting following error after deploying ear file in Sun application server8. Please let me know the solution if any one of you faced this type of problem... [#|2004-09-30T16:24:37.218+0530|WARNING|sun-appserver-pe8.0.0_01|javax.enterprise.system.t

  • My ios 5 update for itouch will not download?

    how do i get it to download

  • How do I shut off automatic HP updates

    Everytime we turn on the computer, HP autmatically updates which takes over an hour, then restarts the computer and updates again.  How can we keep it from doing that, we don't want the updates?  We have a 6310E desktop purchased in 2010.