Introduced
The Java platform implements the socket in the java.net package. In this article, we'll work with the following three classes in the Java.net package:
· URLConnection
· Socket
· ServerSocket
There are more classes in the java.net package, but these are the things that you most often encounter, let's start with URLConnection, which provides a way to use the socket in your Java code without knowing the underlying mechanism of the socket.
You can use sockets without even trying.
Connecting to a URL involves the following steps:
• Create a URLConnection
• Configure it with a different setter method
• Connect to URLConnection
• Interacting with different getter methods
Below, let's use some examples to demonstrate how to use URLConnection to request a document from a single server.
Urlclient class
We'll start with the structure of the Urlclient class.
import java.io.*;
import java.net.*;
public class URLClient {
protected URLConnection connection;
public static void main(String[] args) {}
public String getDocumentAt(String urlString) {}
}
Note: You must import the java.net and java.io packages first.
We give our class an instance variable used to save a urlconnection
Our class contains a main () method to handle the logical stream of browsing a document (logic flow), our class also contains the Getdocumentat () method for connecting to the server and requesting documents, and we'll explore the details of these methods below.
Browse documents
The main () method is used to process the logical stream of browsing a document (logic flow):
public static void main(String[] args) {
URLClient client = new URLClient();
String yahoo = client.getDocumentAt("http://www.yahoo.com");
System.out.println(yahoo);
}
Our main () method simply creates a new instance of the Urlclient class and uses a valid URL string to invoke the Getdocumentat () method. When the call returns the document, we store it in a string and output the string to the console. However, the actual work is done in the Getdocumentat () method.