0

I've tried to download HTML content from the URL http://google.com and another URL.

I tried:

URL url = new URL("http://google.com/");
urlConnection = (HttpURLConnection) url.openConnection();

And although I've tried InputStream, it didn't work the same.

try {

    URL url = new URL("http://google.com/");

        urlConnection = (HttpURLConnection) url.openConnection();

        urlConnection.setDoOutput(true);
        urlConnection.setChunkedStreamingMode(0);

        InputStream in = new BufferedInputStream(urlConnection.getInputStream());

        System.out.print(urlConnection.getResponseCode());


    }
    catch (Exception e)
    {
        System.out.print("Error: "+e.getMessage());
    }
    finally {
        urlConnection.disconnect();
    }

At the end I see the catch and the e.getMessage is null. If I debug it, urlConnection.getResponseCode() is returning -1.

Robin Green
  • 32,079
  • 16
  • 104
  • 187
  • 2
    Use `e.printStackTrace()`, rather than `System.out.print("Error: "+e.getMessage());`. You are throwing away lots of useful information (e.g. the type of the exception). – Andy Turner Feb 03 '16 at 14:34
  • Possible duplicate of [How to fetch HTML in Java](http://stackoverflow.com/questions/31462/how-to-fetch-html-in-java) – Joopkins Feb 03 '16 at 15:23
  • Possible duplicate of [How to download and save a file from Internet using Java?](https://stackoverflow.com/questions/921262/how-to-download-and-save-a-file-from-internet-using-java) – Robin Green Nov 17 '18 at 06:41

1 Answers1

0

You set DoOutput where you will not do output. You do not set DoInput where you do input. Remove the chunked streaming mode.

greenapps
  • 11,154
  • 2
  • 16
  • 19