K
K
kukarekuu2016-12-16 16:00:33
Java
kukarekuu, 2016-12-16 16:00:33

How to get the content of a webpage in Java?

I want to get the content of a web page from a specific resource, for example, yandex.ru
Here's the code:

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.*;
public class pageFromSite {
 
    public static void main(String[] args) throws Exception {
        URL url = new URL("http://yandex.ru/");
        BufferedReader reader = new BufferedReader(new InputStreamReader(url.openConnection().getInputStream(), "UTF-8"));
        while (true) {
            String line = reader.readLine();
            if (line == null)
                break;
            System.out.println(line);
        }
    }
}

Compiles successfully, but after running it throws an error:
Exception in thread "main" java.net.SocketException: Socket is not connected: co
nnect
at java.net.DualStackPlainSocketImpl.connect0(Native Method)
at java.net.DualStackPlainSocketImpl.socketConnect(Unknown Source)
at java.net.AbstractPlainSocketImpl.doConnect(Unknown Source)
at java.net.AbstractPlainSocketImpl.connectToAddress(Unknown Source)
at java.net.AbstractPlainSocketImpl.connect(Unknown Source)
at java.net.PlainSocketImpl.connect(Unknown Source)
at java.net.SocksSocketImpl.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at sun.net.NetworkClient.doConnect(Unknown Source)
at sun.net.www.http.HttpClient.openServer(Unknown Source)
at sun.net.www.http.HttpClient .openServer(Unknown Source)
at sun.net.www.http.HttpClient.(Unknown Source)
at sun.net.www.http.HttpClient.New(Unknown Source)
at sun.net.www.http.HttpClient.New( Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.getNewHttpClient(Unknown
Source)
at sun.net.www.protocol.http.HttpURLConnection.plainConnect0(Unknown Sou
rce)
at sun.net.www.protocol.http .HttpURLConnection.plainConnect(Unknown Sour
What could be the problem ?

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question