Networking In Java the java.net class and working with URL


Java comes with java.net package which allows you to work with the network available on the system. Java gives you access to the application, transport and link layer. the URL is an important entity when you work with web application and web services so this article introduces you with the java.net and URL class.

The Java was when created with the focus on the Internet technologies and focus on platform independence. The Java founders know it would not be what it is without the networking support. However the applets work automatically on the browsers in a well manner without using much of the networking. But the Applets work on the application level.

Yes, there are levels in the networking and Java provide you the support for all the levels of networking. Yes there is 7 level model of the network but it is reduced down to 4 level model of networking when you want an abstract model. The following figure shows the network layer model which will also tell you what work at what level.

Networking Model

So As you see in the figure above Java developers think so much about you and take off the load from your head. Well. In this Article we are going to look at the basics of networking which will include the use of the URL class form java.net package. The URL is and important factor if you want to create a web service.

So in this part we are going to introduce you with the URL and basics of TCP and UDP protocols because you must know them before you get to know the Socket and Datagrams.

URL

The URL stands for the Uniform Resource locater this is formed of different part which includes the protocol, domain, port number and the path. A domain usually points to a root unless we are not using any path with it. The port number is optional.

URL Format

The URL is also a class provided with the java.net package. When you create a URL object using a URL address, Java gives us so much to know about that URL address. The URL class provides several methods to obtain info regarding the URL. as shown in following program.


package networking;
import java.net.*;
import java.io.*;
public class URLClass {
    public static void main(String[] args){
        try{
            URL google = new URL("http://localhost/work/test.php?string=hello");
            System.out.println(google.getAuthority());
            System.out.println(google.getContent());
            System.out.println(google.getDefaultPort());
            System.out.println(google.getFile());
            System.out.println(google.getPath());
            System.out.println(google.getProtocol());
            System.out.println(google.getHost());
            System.out.println(google.getQuery());
        }
        catch(Exception e){
            System.out.println(e);
        }
    }
}

As you see there are several methods to extract the general information from the URL. Here is what each method returns.

localhost
sun.net.www.protocol.http.HttpURLConnection$HttpInputStream@5d1ddcf4
80
/work/test.php?string=hello
/work/test.php
http
localhost
string=hello

Note: I have used a sample php page to demonstrate, however if you know nothing about the php you can use the java or any of your known URL from Internet, for example you can use www.google.com also.

Another point to pay attention is the Content part. It returns an object of type HttpInputStream or HttpConnection. You can cast them to use or else you can get the connection or stream using the method provided openConnection() or openStream(). Both these methods are handy if you want to read some information from the URL, however you want to write data also then only openConnection() will help you as we see in the following program. We will pass the parameter which means we will open the connection and will write the data on the URL.

The result we get will be depending upon the parameter we pass. Let me first show you the Script which I have created at the server which will process the request.


<?php
if(isset($_REQUEST['string'])){
	echo $_REQUEST['string'];
}
else{
	echo "nothing";
}
?>

this creates a php script which will check if there is some Request parameter set in the URL if so it will echo the value of that query, and if not this will print 'nothing'. You can create anything or any type of script you like. or better try to do some ready made script on Internet which you may find easily.

Now here is what we do with the java program.


package networking;
import java.net.*;
import java.io.*;
public class URLClass {
    public static void main(String[] args){
        try{
            URL google = new URL("http://localhost/work/test.php");
            URLConnection yc = google.openConnection();
            yc.setDoOutput(true);
            OutputStreamWriter os = new OutputStreamWriter(yc.getOutputStream());
            os.write("string=hello world");
            os.close();
            BufferedReader bs = new BufferedReader(new InputStreamReader(yc.getInputStream()));
            String s;
            while((s=bs.readLine())!=null){
                System.out.println(s);
            }
            
        }
        catch(Exception e){
            System.out.println(e);
        }
    }
}

you will find everything same up to creating URL object and handling exception. We have opened a connection to that URL and using that connection we will be reading and writing to that URL address. As you see We have set the Outputting capability of the URL. and Get the OutputStream as well as InputStream on that URL using the connection object. Then We write a string to the url and this string acts as the query string and will compile the response accordingly. Then we open the input stream and read the response. which prints

hello world

Note: It is necessary to handle the exception because URL constructor may throw a MalformedURLException.

TCP

TCP is the protocol which work at transport layer of the networking model. The work is to make sure the data is delivered properly. Now the problem is it waits for the acknowledgement and hence is slower at time. The Java provide the Socket and ServerSocket classes which works in accordance of this protocol to provide the reliable transmission. TCP is reliable connection for the chat like program. It needs the handshake between the client and servers before the transmission takes place.

UDP

The UDP stand for User Datagram protocol. This is kind of non reliable protocol. The data is sent in the form of packet and the delivery is completely reliable on the Internet Protocol. The UDP does not waits for the acknowledgement of the previously sent packet, neither it cares if the data arrives in improper order. The DatagramSocket and DatagramPacket are the classes provided in the Java.net package to support the UDP.