First, the summary
"Reference: Http://www.cnblogs.com/oubo/archive/2012/01/16/2394641.html"
Second, Java Network programming common class
1.InteAddress class
(1) Important API:
static InetAddress[] |
getAllByName(String host)Given the name of a host, returns an array of it IP addresses, based on the configured name service on the system. |
static InetAddress |
getByAddress(byte[] addr)Returns an InetAddress object given the raw IP address. |
static InetAddress |
getByAddress(String host, byte[] addr)Creates an inetaddress based on the provided host name and IP address. |
static InetAddress |
getByName(String host)Determines the IP address of a host, given the host ' s name. |
String |
getCanonicalHostName()Gets the fully qualified domain name for this IP address. |
String |
getHostAddress()Returns the IP address string in textual presentation. |
String |
getHostName()Gets the host name for this IP address. |
boolean |
isReachable(int timeout)Test whether that address is reachable. |
boolean |
isReachable(NetworkInterface netif, int ttl, int timeout)Test whether that address is reachable. |
(2) Example
Packagejavanet;Importjava.net.InetAddress; Public classtestinetaddress{ Public Static voidMain (string[] args)throwsexception{inetaddress IP=inetaddress.getbyname ("www.baidu.com"); System.out.println (ip.gethostaddress ()+","+ip.gethostname ()); System.out.println (Ip.getcanonicalhostname ()); System.out.println ("Baidu can reach:" + ip.isreachable (2000)); //returns an array of the corresponding IP addresses for a given serverInetaddress[] Ip2=inetaddress.getallbyname ("www.baidu.com"); for(inetaddress u:ip2) System.out.println (u.tostring ()); InetAddress Local= Inetaddress.getbyaddress (New byte[]{127,0,0,1}); System.out.println (local.gethostaddress ()+","+local.gethostname ()); System.out.println (Local.getcanonicalhostname ()); System.out.println ("Is this machine up to:" + local.isreachable (3000)); }}
2.URL class
(1) The composition of the URL
Protocol://resourcename
The Protocol name (protocol) indicates the transport protocol used to obtain the resource, such as HTTP, FTP, Gopher, file, and so on, and the Resource name (resourcename) should be the full address of the resource, including the hostname, port number, file name, or a reference inside the file. For example:
http://www.sun.com/protocol Name://Host Name
Http://home.netscape.com/home/welcome.html protocol Name://Machine name + file name
Http://www.gamelan.com:80/Gamelan/network.html#BOTTOM protocol Name://Machine name + port number + file name + Internal reference.
(2) Important API
Add: URL Class Construction Method:<1>URL(String protocol, String host, int port, String file, URLStreamHandler handler)
Creates a URL object from the specified protocol , host , number port , file and handler .
<2>URL(URL context, String spec, URLStreamHandler handler)
Creates a URL by parsing the given spec with the specified handler within a specified context.<3>
URLConnection |
openConnection()Returns a URLConnection instance that represents a connection to the remote object referred to by the URL . |
URLConnection |
openConnection(Proxy proxy)Same openConnection() as, except that the connection would be made through the specified proxy; Protocol handlers that does not support proxing would ignore the proxy parameter and make a normal connection. |
(3) Example
<1> public URL (String spec);
A URL object can be constructed from a string that represents a URL address.
URL urlbase=new url ("http://www. 263.net/")
<2> public URL (URL context, String spec);
Constructs a URL object from a base URL and a relative URL.
URL net263=new url ("http://www.263.net/");
URL index263=new url (net263, "index.html")
<3> public URL (String protocol, string host, string file);
The new URL ("http", "www.gamelan.com", "/pages/gamelan.net"). HTML ");
<4> public URL (String protocol, string host, int port, string file);
URL gamelan=new url ("http", "www.gamelan.com", "pages/gamelan.network.html");
Note: The constructor of the class URL declares that it discards the non-runtime exception (malformedurlexception), so when generating the URL object, we have to deal with this exception, usually with the Try-catch statement. The format is as follows:
try{
URL myurl= new URL (...)
}catch (Malformedurlexception e) {
... }
Importjava.net.*;ImportJava.io.*; Public classurldemo{ Public Static voidmain (String [] args) {Try{URL URL=NewURL ("Http://www.w3cschool.cc/index.html?language=cn#j2se"); System.out.println ("URL is" +url.tostring ()); System.out.println ("Protocol is" +Url.getprotocol ()); System.out.println ("Authority is" +url.getauthority ()); System.out.println ("File name is" +url.getfile ()); System.out.println ("Host is" +url.gethost ()); System.out.println ("Path is" +Url.getpath ()); System.out.println ("Port is" +Url.getport ()); System.out.println ("Default port is" +Url.getdefaultport ()); System.out.println ("Query is" +url.getquery ()); System.out.println ("Ref is" +url.getref ()); }Catch(IOException e) {e.printstacktrace (); } }}
3.URLConnection class
(1) OpenConnection () returns a java.net.URLConnection.
For example:
-
If you connect the URL of the HTTP protocol, the OpenConnection () method returns the HttpURLConnection object.
-
If the URL you are connecting to is a JAR file, the OpenConnection () method returns the Jarurlconnection object.
(2) Important API
(3) Example
Importjava.net.*;ImportJava.io.*; Public classurlconndemo{ Public Static voidmain (String [] args) {//1. Request to send a GET method to a specified URL Try { //Create a URL objectURL url =NewURL ("http://www.w3cschool.cc"); //Establish a URL connectionURLConnection URLConnection =url.openconnection (); HttpURLConnection Connection=NULL; if(URLConnectioninstanceofhttpurlconnection) {Connection=(httpurlconnection) URLConnection; } Else{System.out.println ("Please enter an HTTP URL."); return; } //create an input stream to get the data get toBufferedReader in =NewBufferedReader (NewInputStreamReader (Connection.getinputstream (), "Utf-8")); String urlstring= ""; String Current=""; while(current = In.readline ())! =NULL) {urlstring+=Current ; } //System.out.println (urlstring); } Catch(IOException e) {e.printstacktrace (); } //2. Send a POST request to the specified URL Try{ //Create a URL objectURL url =NewURL ("Http://sso.jwc.whut.edu.cn/Certification//login.do"); //Establish a URL connectionURLConnection UrlConnection2 =url.openconnection (); HttpURLConnection Connection2=NULL; if(UrlConnection2instanceofhttpurlconnection) {Connection2=(httpurlconnection) UrlConnection2; } Else{System.out.println ("Please enter an HTTP URL."); return; } //to send a POST request, you must set the following two linesConnection2.setdooutput (true); Connection2.setdoinput (true); //gets the output stream corresponding to the URLConnection objectPrintWriter out =NewPrintWriter (Connection2.getoutputstream ()); //Send Request ParametersString postdata= "username=0121201030106&password=0121201030106&type=xs&imagefield.x=60& Imagefield.y=19 "; Out.print (PostData); //buffer for flush output streamOut.flush (); //create an input stream to get the data get toBufferedReader in =NewBufferedReader (NewInputStreamReader (Connection2.getinputstream (), "Utf-8")); String urlString2= ""; String Current=""; while(current = In.readline ())! =NULL) {urlString2+=Current ; } System.out.println (URLSTRING2); } Catch(IOException e) {e.printstacktrace (); } }}
4.URLEncoder class and Urldecoder class
(1) Important API
Urlencoder
static string |
encode (string s) DEPRECATED.&NBSP; the resulting string may vary depending on the platform ' s default encoding. Instead, use the Encode (string,string) method to specify the encoding. |
static string |
encode (string s, string enc) Translates a string into application/x-www-form-urlencoded format using a specific encoding Scheme. |
The second encode method may throw a unsupportedencodingexception
Urldecoder
Construction method: Urldecoder ()
static String |
decode(String s)Deprecated. The resulting string may vary depending on the platform ' s default encoding. Instead, use the decode (string,string) method to specify the encoding. |
static String |
decode(String s, String enc)Decodes a application/x-www-form-urlencoded string using a specific encoding scheme. |
Reference: 1) HTTP://DOCS.ORACLE.COM/JAVASE/8/DOCS/API/2) http://www.w3cschool.cc/java/java-url-processing.html 3) htt p://blog.csdn.net/chenzheng_java/article/details/6248066
Java Network Programming (i)