首页 > 代码库 > Java网络编程(一)
Java网络编程(一)
一、综述
【参考:http://www.cnblogs.com/oubo/archive/2012/01/16/2394641.html】
二、Java网络编程常用类
1.InteAddress类
(1)重要API:
static InetAddress[] | getAllByName(String host) Given the name of a host, returns an array of its 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)举例
package javanet;import java.net.InetAddress;public class TestInetAddress{ public static void main(String[] args)throws Exception{ InetAddress ip=InetAddress.getByName("www.baidu.com"); System.out.println(ip.getHostAddress()+","+ip.getHostName()); System.out.println(ip.getCanonicalHostName()); System.out.println("百度是否可达:" + ip.isReachable(2000)); //返回给定服务器对应IP地址组成的数组 InetAddress[] 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("本机是否可达:" + local.isReachable(3000)); }}
2.URL类
(1)URL的组成
protocol://resourceName
协议名(protocol)指明获取资源所使用的传输协议,如http、ftp、gopher、file等,资源名(resourceName)则应该是资源的完整地址,包括主机名、端口号、文件名或文件内部的一个引用。例如:
http://www.sun.com/ 协议名://主机名
http://home.netscape.com/home/welcome.html 协议名://机器名+文件名
http://www.gamelan.com:80/Gamelan/network.html#BOTTOM 协议名://机器名+端口号+文件名+内部引用.
(2)重要API
补充:URL类构造方法:<1>URL(String protocol, String host, int port, String file, URLStreamHandler handler)
Creates a
URL
object from the specified protocol
, host
, port
number, file
, and handler
.
<2>URL(URL context, String spec, URLStreamHandler handler)
URLConnection | openConnection() Returns a URLConnection instance that represents a connection to the remote object referred to by theURL . |
URLConnection | openConnection(Proxy proxy) Same as openConnection() , except that the connection will be made through the specified proxy; Protocol handlers that do not support proxing will ignore the proxy parameter and make a normal connection. |
<1> public URL (String spec);
通过一个表示URL地址的字符串可以构造一个URL对象。
URL urlBase=new URL("http://www. 263.net/")
<2> public URL(URL context, String spec);
通过基URL和相对URL构造一个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);
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", 80, "Pages/Gamelan.network.html");
注意:类URL的构造方法都声明抛弃非运行时例外(MalformedURLException),因此生成URL对象时,我们必须要对这一例外进行处理,通常是用try-catch语句进行捕获。格式如下:
try{
URL myURL= new URL(…)
}catch (MalformedURLException e){
… }
import java.net.*;import java.io.*;public class URLDemo{ public static void main(String [] args) { try { URL url = new URL("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类
(1)openConnection() 返回一个 java.net.URLConnection。
例如:
如果你连接HTTP协议的URL, openConnection() 方法返回 HttpURLConnection 对象。
如果你连接的URL为一个 JAR 文件, openConnection() 方法将返回 JarURLConnection 对象。
- 等等...
(2)重要API
(3)举例
import java.net.*;import java.io.*;public class URLConnDemo{ public static void main(String [] args) { //1. 向指定URL发送GET方法的请求 try { //创建URL对象 URL url = new URL("http://www.w3cschool.cc"); //建立URL连接 URLConnection urlConnection = url.openConnection(); HttpURLConnection connection = null; if(urlConnection instanceof HttpURLConnection) { connection = (HttpURLConnection) urlConnection; } else { System.out.println("Please enter an HTTP URL."); return; } //创建输入流来获取GET到的数据 BufferedReader in = new BufferedReader(new InputStreamReader(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.向指定URL发送POST请求 try{ //创建URL对象 URL url = new URL("http://sso.jwc.whut.edu.cn/Certification//login.do"); //建立URL连接 URLConnection urlConnection2 = url.openConnection(); HttpURLConnection connection2 = null; if(urlConnection2 instanceof HttpURLConnection) { connection2 = (HttpURLConnection) urlConnection2; } else { System.out.println("Please enter an HTTP URL."); return; } //发送POST请求必须设置如下两行 connection2.setDoOutput(true); connection2.setDoInput(true); //获取URLConnection对象对应的输出流 PrintWriter out = new PrintWriter(connection2.getOutputStream()); //发送请求参数 String postdata="http://www.mamicode.com/userName=0121201030106&password=0121201030106&type=xs&imageField.x=60&imageField.y=19"; out.print(postdata); //flush输出流的缓冲 out.flush(); //创建输入流来获取GET到的数据 BufferedReader in = new BufferedReader(new InputStreamReader(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类和URLDecoder类
(1)重要API
URLEncoder
static String | encode(String s) Deprecated. 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. |
第二个encode方法可能会抛出UnsupportedEncodingException
URLDecoder
构造方法: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. |
参考:1)http://docs.oracle.com/javase/8/docs/api/
Java网络编程(一)