2

I am trying to download pdf from a url using java. I am using the following code for the same. I am able to download the pdf.

But the problem is that I am not able to read the pdf using the adobe reader because the content type of the url is application/pdf ; charset= utf-8.

Although for all the urls whose content type is not the same as above, I am able to download as well as read the pdf.

public class PdfDownloading 
{
    public static void DownloadPDFFromURL(String link)
    {
        try
        {
            URL url = new URL(link);
            InputStream in = url.openStream();
            FileOutputStream fos = new FileOutputStream(new File("E:\\KOLDump\\charles_hicks\\pdfs\\"+"hello"+".pdf"));
            int length = -1;
            byte[] buffer = new byte[50000];// buffer for portion of data from connection
            while ((length = in.read(buffer)) > -1) {
                fos.write(buffer, 0, length);
            }
            fos.close();
            in.close();
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }

    }
    public static void main(String [] args)
    {
        DownloadPDFFromURL("http://www.amjmed.com/article/S0002-9343(06)00676-0/pdf");
    }

}

The url from which I am not able to download the pdf is given in the code itself.

paisanco
  • 4,098
  • 6
  • 27
  • 33
RushilAhuja
  • 35
  • 1
  • 9
  • Instead of `fos` write the code in `System.out`. You will see what happens.. http://stackoverflow.com/questions/1884230/java-doesnt-follow-redirect-in-urlconnection – Ramesh-X Dec 12 '15 at 18:41
  • *application/pdf ; charset= utf-8* - as a side note: if you really get that type declaration, please tell the server administrator to correct his settings. A pdf is a binary format, so a charset does not make sense. – mkl Dec 12 '15 at 19:30
  • @Ramesh-X : When I print the data, I get the link saying that the link has been moved to the the link that is getting printed.When I give that link in the code and again print the data it again says that this link has been moved to another link and when i open both the links I am being redirected to the link that is there in the code above. – RushilAhuja Dec 13 '15 at 11:13
  • You `http` link redirects to a `https` link and that cannot be handled with java as I know of. Refer the link I gave. That question is about redirecting `http` to `https` – Ramesh-X Dec 13 '15 at 16:58

0 Answers0