Java Network Classes Part2
Java Networking Tutorial
Goto Part1
HttpURLConnection class
It is the subclass URLConnection
Provides support for HTTP connctions on port 80.
to open a connection we use openConnection on a URL object
and must cast the result to HttpURLConnection.
methods
getRequestMethod()
getResponseCode()
getResponseMessage()
getHeaderFields()
import java.net.*; import java.io.*; public class HttpURLDemo { public static void main(String[] args) throws IOException { URL hp = new URL("http://www.google.com"); HttURLConnection hpCon = (HttpURLDemo) hp.openConnection(); System.out.println("Request method is"+hpCon.getRequestMethod()); System.out.println("Response code is"+hpCon.getResponseCode()); System.out.println("Requst method is"+hpCon.getResponseMessage()); Map<String>,List<String> hdrMap=hpCon.getHeaderFields()); Set<String> hdrField = hdrMap.keySet(); System.out.println("Here is the header:"); for(String k:hdrField){ System.out.println("Key:"+k+"Value:"+hdrMap.get(k)); } } }
URI (UniformResourceIdentifier) class
It is a part of URL.
Similar to URLs. URL contains the URIs. It is a standard way of identifing resource.
TCP/IP ServerSockets
Client and server communicates using 2 classes.
1. Socket → used by client, to communicate with server.
2. ServerSocket → listens for either local/remote client program to connect to them. it has a method called accept().
GET any URL using SOCKET connection from a JAVA Program
This Java example shows how to GET content from any URL using SOCKET connection
from a Java porgram.
import java.net.*; import java.io.*; import java.util.*; public class Socketget { public static void main(String[] args) throws Exception { try { Socket socket = new Socket("www.oracle.com",80); PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()))); out.println("GET /index.html HTTP/1.0"); out.println(); out.flush(); BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream())); String inputLine; int count = 0; while ((inputLine = in.readLine()) != null) { count++; System.out.println(count); System.out.print(inputLine); } in.close(); System.out.println("PRINTING HERE!!!"); } catch (Exception e) { e.printStackTrace(); } } }
Find WHOIS information of any domain from a JAVA Program
//Demonstrate Socket class import java.net.*; import java.io.*; class Whois{ public static void main(String args[]) throws Exception{ int c; Socket s = new Socket("whois.oracle.com",43); InputStream in = s.getInputStream(); OutputStream out = s.getOutputStream(); String str=(args.length==0?"oracle.com": args[0]+"\n"; byte buf[] = str.getBytes(); out.write(buf); while((c=in.read())!= -1){ System.out.println((char)c); } s.close(); } }
Java Networks Home
Java Tutorial Home
Goto Part1
Comments
Post a Comment