Computer Science, asked by duragpalsingh, 1 year ago

How to connect java with any webpage?

Answers

Answered by Anonymous
0
Connecting to a URL

After you've successfully created a URLobject, you can call the URL object's openConnection method to get a URLConnection object, or one of its protocol specific subclasses, e.g.java.net.HttpURLConnection

You can use this URLConnection object to setup parameters and general request properties that you may need before connecting. Connection to the remote object represented by the URL is only initiated when the URLConnection.connectmethod is called. When you do this you are initializing a communication link between your Java program and the URL over the network. For example, the following code opens a connection to the site example.com:

try { URL myURL = new URL("http://example.com/"); URLConnection myURLConnection = myURL.openConnection(); myURLConnection.connect(); } catch (MalformedURLException e) { // new URL() failed // ... } catch (IOException e) { // openConnection() failed // ... }

A new URLConnection object is created every time by calling the openConnectionmethod of the protocol handler for this URL.

You are not always required to explicitly call the connect method to initiate the connection. Operations that depend on being connected, like getInputStream, getOutputStream, etc, will implicitly perform the connection, if necessary.

Now that you've successfully connected to your URL, you can use the URLConnection

hope this may help you.@
mark as brainliest if u liked this#^
Answered by ans81
0
HEY MATE HERE IS YOUR ANSWER

___
The simplest solution (without depending on any third-party library or platform) is to create a URL instance pointing to the web page / link you want to download, and read the content using streams.

For example:

{ // Make a URL to the web page URL url = new URL("http://stackoverflow.com/questions/6159118/using-java-to-pull-data-from-a-webpage"); // Get the input stream through URL Connection URLConnection con = url.openConnection(); InputStream is =con.getInputStream(); // Once you have the Input Stream, it's just plain old Java IO stuff. // For this case, since you are interested in getting plain-text web page // I'll use a reader and output the text content to System.out. // For binary content, it's better to directly read the bytes from stream and write // to the target file. BufferedReader br = new BufferedReader(new InputStreamReader(is)); String line = null; // read each line and write to System.out while ((line = br.readLine()) != null) { System.out.println(line); } } }

Hope this helps.

Similar questions