网络编程(一)

一、JDK中的网络类

  • 通过java.net包中的类,java程序能够使用TCP或UDP协议在互联网上进行通讯;
  • Java通过扩展已有的流式输入/输出接口和增加在网络上建立输入/输出对象特性这两个方法支持TCP/IP;
  • Java支持TCP和UDP协议族。TCP用于网络的可靠的流式输入/输出。UDP支持更简单、快速的、点对点的数据报模式。

二、创建和使用URL访问网上资源

1、什么是URL?

  • URL(Uniform Resource Locator)是统一资源定位符的简称,它表示Internet上某一资源的地址。通过URL我们可以访问Internet上的各种网络资源,比如常见的www,ftp站点。浏览器通过解析给定的URL可以在网络上查找响应的文件或其他资源。
  • URL是最为直观的一种网络定位方法。在目前使用最为广泛的TCP/IP中对于URL中主机名的解析也是协议的一个标准,即所谓的域名解析服务。

2、URL的两个主要部分

(1)协议标识符

http,ftp,file等

(2)资源名字

主机名,文件名,端口号,引用
例如:http://java.sun.com:80/docs/books/tutorial/index.html#DOWN

3、创建URL

  • Java中,可以创建表示URL地址的URL对象。URL对象表示一个绝对URL路径,但是可以用绝对URL、相对URL和部分URL构建。
  • 创建URL示例
    例如现在有这样一个地址:http://www.gamelan.com/pages/index..html
//第一种方法
new URL("http://www.gamelan.com/pages/index.html");

//第二种方法
URL gamelan = new URL("http://www.gamelan.com/pages/");
URL gamelanGames = new URL(gamelan, "game.html");

//第三种方法
new URL("http", "www.gamelan.com", "/pages/index.html");

//第四种方法
new URL("http", "www.gamelan.com", 80, "pages/index.network.html");
  • 如果创建失败
try
{
   URL myURL = new URL(. . .)
} catch (MalformedURLException e)
{
 . . .
 // exception handler code here
. . .
}
  • 程序Url1展示了如何获得URL对象的各个属性
import java.net.URL;

public class Url1
{
    public static void main(String[] args) throws Exception
    {
        URL url = new URL(""
                + "http://java.sun.com:80/docs/books/tutorial/index.html#DOWN");
        
        //获得协议标识符
        String protocol = url.getProtocol();
        //获得主机地址
        String host = url.getHost();
        //获得文件名
        String file = url.getFile();
        //获得端口号
        int port = url.getPort();
        //获得引用
        String ref = url.getRef();
        
        System.out.println(protocol + " ," + host + " ," + 
                                file + " , " + port +" ," + ref);
        
    }
}

程序运行结果如下:


image.png

4、URLConnection

  • URL的openConnection方法可以创建一个URLConnection对象,用该对象可以获取URL实际比特或内容信息。
url.openConnection()
  • openConnection()有下面的常用形式:
URLConnection openConnection()
  • 与调用URL对象相关,它返回一个URLLConnection对象。它可能引发IOException异常。

  • URLConnection是访问远程资源属性的一般用途的类。如果建立了与远程服务器之间的连接,就可以在传输它到本地之前用URLConnection来检查远程对象的属性。这些属性由HTTP协议规范定义并且仅对用HTTP协议的URL对象有意义。

(1)程序UrlConnection1,通过URL和URLConnection建立与HTTP服务器的连接来获取信息:
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;

public class UrlConnection1
{
    public static void main(String[] args) throws Exception
    {
        URL url = new URL("http://www.qq.com");
        
        //通过连接得到网页的字节输入流
        URLConnection conn = url.openConnection();
        InputStream is = conn.getInputStream();
        
        OutputStream os = new FileOutputStream("qq.html");
        
        byte[] buffer = new byte[2048];
        int lenth = 0;
        
        //通过字节文件输出流将网页内容写到文件中
        while ((lenth = is.read(buffer, 0, buffer.length)) != -1)
        {
            os.write(buffer, 0, lenth);
        }
        
        is.close();
        os.close();
    }
}
  • 程序UrlConnection1中,其实可以直接通过URL的openStream()方法得到网页的输入流
InputStream is = url.openStream();

用上面一行代码替换UrlConnection1中的下面两行代码

URLConnection conn = url.openConnection();
InputStream is = conn.getInputStream();
(2)UrlConnection2用字符流替换UrlConnection1的字节流实现其功能
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;

public class UrlConnection2
{
    public static void main(String[] args) throws Exception
    {
        URL url = new URL("http://www.sohu.com");
            
        //构建缓冲字符流
        BufferedReader bf = new BufferedReader(
                new InputStreamReader(url.openStream()));
        
        String line = null;
        while ((line = bf.readLine()) != null)
        {
            System.out.println(line);
        }
        
        bf.close();
    }
}

三、InetAddress

  • InetAddress类用来封装我们前面讨论的数字式的IP地址和该地址的域名。通过ip主机名与这个类发生作用,IP主机名比它的IP地址用起来更简便更容易理解。

  • InetAddress类内部隐藏了地址数字。

1、工厂方法

  • InetAddress类没有明显的构造函数。为生成一个InetAddress对象,必须运用一个可用的工厂方法。

-工厂方法仅是一个类中静态方法返回一个该类实例的约定。对于InetAddress,三个方法getLocalHost()、getByName()以及getAllByName()可以用来创建InetAddress的实例。

  • 程序InetAddressTest展示了getLocalHost()、getAllByName()的用法
import java.net.InetAddress;

public class InetAddressTest
{
        public static void main(String[] args) throws Exception
        {
            //InetAddress.getLocalHost()仅返回象征本地主机的InetAddress
            InetAddress inetAddress = InetAddress.getLocalHost();
            
            System.out.println(inetAddress);
            
            //InetAddress.getByName()返回一个传给它的主机名的InetAddress
            inetAddress = InetAddress.getByName("www.sohu.com");
            System.out.println(inetAddress);
            
        }
}

你可能感兴趣的:(网络编程(一))