Java的基本网络支持

前端时间看了一下Java的网络编程,这里简单的写一些有关java基本网络支持:

网络基础知识:

  计算机网络:计算机网络是把分布在不同地理区域的计算机与专门在外部设备用通信线路互联成一个规模大,功能强的网络系统。计算机网络可以提供以下一些主要功能:

   1. 资源共享

   2. 信息传输与集中处理

   3. 均衡负荷与分布处理

   4. 综合信息服务。

  通信协议:计算机网络中实现通信必须有一些约定,这些约定称之为通信协议。通信协议负责对传输速率,传输代码,代码结构,传输步骤,出错控制等指定处理标准。通信协议通常由三部分组成,1,语义部分,用于决定双方对话的类型;2,语法部分,用于决定双方对话的格式;3,变换规则,用于决定通信双方的应答关系

   IP协议:IP(Internet Protocol)协议 又称互联网协议,是支持网间互联的数据报协议。它提供网间连接的完善功能,包括IP数据包规定互联网范围内的地址格式

   TCP协议:TCP(Transmission Control Protocol)协议,即传输控制协议,它规定一种可靠的数据信息传递服务。

          尽管IP协议与TCP协议功能不尽相同,也可以分开单独使用,但它们是同一时期作为一个协议来设计的,并且功能上也是互补。因此实际上常常把这两个协议统称为TCP/IP协议,是Internet种最常用的基础协议

  网络结构模型:在1978年,ISO(国际标准化组织)提出了“开放系统互联参考模型”(Open System Interconnection),将网络分成了物理层,数据链路层,网络层,传输层,会话层,表示层,以及应用层7层。如下图:

 

   除“开放系统互联参考模型”(Open System Interconnection)之外,TCP/IP也制定了网络结构模型,并将网络分了四层,下图是TCP/IP分层模型与OSI分层模型的对应关系:

            

InetAdress 类:

   Java提供InetAdress类来代表IP地址(IP地址是用于标识网络种的一个通信实体,是IP协议提供的一种统一的地址格式)。该类本身没有提供太多功能,它代表IP地址对象,是网络通讯的基础。

public class Net{
    /**
     * 使用InetAddress类代表IP地址
     * InetAddress本身没有太多的功能,它代表一个IP地址对象,后期会大量用到该类
     * @throws Exception 
     * */
    public void inetAddress() throws Exception{
        System.out.println("---------InetAddress---------");
        //根据主机名获取对应的InetAddress实例
        InetAddress inetAddress = InetAddress.getByName("www.hjlin.com");
        System.out.println(inetAddress);
        System.out.println("是否可抵达"+inetAddress.isReachable(5000));
        inetAddress = InetAddress.getByAddress(new byte[]{127,0,0,1});
        System.out.println(inetAddress);
        System.out.println(inetAddress.getCanonicalHostName());
    }
    public static void main(String[] args){
        try{
            Net net = new Net();
            net.inetAddress();
        }catch(Exception e){}
    }

}

运行结果如下:

---------InetAddress---------
www.hjlin.com/120.78.76.209
是否可抵达true
/127.0.0.1
127.0.0.1

URLDecoder与URLEncoder类:

   Java提供URLDecoder与URLEncoder类用于互联网传输地址(application/x-www-form-urlencoded MIME)的编码(URLEncoder)和反编码(URLDecoder)。

public class Net{
    /**
     * URLDecoder,将application/x-www-form-urlencoded MIME字符串转换为普通字符串
     * URLEncoder,将普通字符串转换为application/x-www-form-urlencoded MIME字符串
     * 用于url地址字符串编码 的转换
     * */
    public void coder() throws UnsupportedEncodingException{
        System.out.println("-------URLDecoder/URLEncoder-------");
        String keyWord = URLEncoder.encode("百度","UTF-8");
        System.out.println(keyWord);
        keyWord = URLDecoder.decode("%E7%99%BE%E5%BA%A6","UTF-8");
        System.out.println(keyWord);
    }
    public static void main(String[] args){
        try{
            Net net = new Net();
            net.coder();
        }catch(Exception e){}
    }
}

运行结果如下:

-------URLDecoder/URLEncoder-------
%E7%99%BE%E5%BA%A6
百度

URL类:

   Java提供URL类来代表统一资源定位器,它是指向互联网“资源”的指针。URL由协议名,主机,端口和资源页组成。即http://www.baidu.com(该端口与资源页都是默认的因此可以访问)

public class Net{
    /**
     * URL,代表统一资源定位器
     * URL可以由:协议名,主机,端口,资源名组成,例如:http://www.hjlin.com/index.html
     * */
    public void url() throws Exception{
        System.out.println("--------url--------");
        URL url = new URL("https://www.baidu.com");
        System.out.println("获取url协议名:"+url.getProtocol());
        System.out.println("获取url主机名:"+url.getHost());
        System.out.println("获取url端口:"+url.getPort());
        System.out.println("获取url资源"+url.getFile());
        System.out.println("获取url路径"+url.getPath());
        System.out.println("获取url查询字符部分"+url.getQuery());
        //打开URL返回InputStream资源
//        InputStream ins = url.openStream();
//        byte[] b = new byte[1024];
//        while(ins.read(b)>0){
//            System.out.println(new String(b));
//        }
//        ins.close();
    }
    public static void main(String[] args){
        try{
            Net net = new Net();
            net.url()
        }catch(Exception e){}
    }
}

运行结果如下:

--------url--------
获取url协议名:https
获取url主机名:www.baidu.com
获取url端口:-1
获取url资源
获取url路径
获取url查询字符部分null

URLConnection类

   java提供URLConnection类用于表示应用程序与URL的通信连接,可以通过URLConnection实例向该URL请求,读取URL的资源。URLConnection对象不能通过URLConnection类进行创建,是通过URL.openConnection方法获取URLConnection对象。

   通常创建一个和URL的连接,并发送请求,读取此URL引用的资源有以下步骤:

  1. 通过URL的openConnection获取URLConnection对象

  2. 设置URLConnection的参数和普通请求

  3. 发出请求,可以使用get请求与post请求

   (1) get请求,直接调用connect方法建立实际连接并发出请求便可

   (2) post请求,需通过获取URLConnection实例对应的输出流进行连接并发送请求

       4. 获取响应资源(响应输入流)并对其处理

这里编写一个get请求与post请求的方式请求URL,并处理URL响应资源。

/**
 * URLConnection 连接对象
 * 可以通过这个连接对象对指定url进行请求并获取url响应的内容
 * 有两种请求方式,一种是get请求,另外一种是post请求
 * */
class UrlConnection{
    URL url = null;
    URLConnection urlConnection;
    
    public UrlConnection(String urlStr){
        try{
            url = new URL(urlStr);
            System.out.println(url);
            urlConnection = url.openConnection();
            System.out.println(urlConnection);
        }catch(Exception e){
            System.out.println("未修改成功");
        }
    }
    
    public void setUrlAndUrlConnection(String urlStr){
        try{
            url = new URL(urlStr);
            System.out.println(url);
            urlConnection = url.openConnection();
            System.out.println(urlConnection);
        }catch(Exception e){
            System.out.println("未创建成功");
        }
    }
    /**
     * URLConnection对象操作get请求
     * 1.设置URLConnection的参数和普通请求属性
     * 2.建立实际连接
     * */
    public void get() throws IOException{
        //设置通用的请求属性
        urlConnection.setRequestProperty("accept", "*/*");
        urlConnection.setRequestProperty("connection", "Keep-Alive");
        urlConnection.setRequestProperty("user-agent","Mozilla/4.0 (compatible; MSIT 6.0; Windows NT 5.1; SV1)");
        
        //建立实际连接
        urlConnection.connect();
        
        //获取响应资源
        response();
    }
    
    /**
     * URLConnection对象操作post请求
     * 1.设置URLConnection的参数和普通请求属性
     * 2.通过输出流来发送请求参数
     * */
    public void post(String param){
        //设置通用的请求属性
        urlConnection.setRequestProperty("accept", "*/*");
        urlConnection.setRequestProperty("connection", "Keep-Alive");
        urlConnection.setRequestProperty("user-agent","Mozilla/4.0 (compatible; MSIT 6.0; Windows NT 5.1; SV1)");
        
        //通过输出流来发送请求参数
        urlConnection.setDoOutput(true);urlConnection.setDoInput(true);
        try {
            PrintWriter printWriter = new PrintWriter(urlConnection.getOutputStream());
            printWriter.print(param);
            printWriter.flush();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        
        response();
    }
    
    /**
     * 读取请求后的响应内容
     * */
    public void response(){
        Map<String, List<String>> map = urlConnection.getHeaderFields();
        for(String key:map.keySet()){
            System.out.println(key+"---->"+map.get(key));
        }
        try {
            BufferedReader in = new BufferedReader(new InputStreamReader(urlConnection.getInputStream(),"utf-8"));
            String result = null;
            while(in.readLine() != null){
                result +="
"+in.readLine();
            }
            System.out.println(result);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            System.out.println("请求出现异常");
            e.printStackTrace();
        }
    }
}
public class Net{
    public static void main(String[] args){
        try{
            String path = "https://www.cnblogs.com/hjlin/";
            String param = "1=1";
            UrlConnection urlConnection = new UrlConnection(path+"?"+param);
//            urlConnection.get();
            path = "www.cnblogs.com";
            urlConnection.setUrlAndUrlConnection(path);
            urlConnection.post(param);
        }catch(Exception e){}
    }  
}

由于响应的是网页,因此可以打印出对应网页的html文件源码。目前对我来说,URL连接都是http开头的协议名,还未尝试过其他的协议名。因此URLConnection只知道使用get与post请求。由想了解HTTP协议的同学,可以去查看相关的资料与书籍,有关于HTTP,java web中会详细介绍,这里不做对HTTP的详细介绍。

完整代码如下:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.InetAddress;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;

/**
 * 网络编程
 * */
/**
 * URLConnection 连接对象
 * 可以通过这个连接对象对指定url进行请求并获取url响应的内容
 * 有两种请求方式,一种是get请求,另外一种是post请求
 * */
class UrlConnection{
    URL url = null;
    URLConnection urlConnection;
    
    public UrlConnection(String urlStr){
        try{
            url = new URL(urlStr);
            System.out.println(url);
            urlConnection = url.openConnection();
            System.out.println(urlConnection);
        }catch(Exception e){
            System.out.println("未修改成功");
        }
    }
    
    public void setUrlAndUrlConnection(String urlStr){
        try{
            url = new URL(urlStr);
            System.out.println(url);
            urlConnection = url.openConnection();
            System.out.println(urlConnection);
        }catch(Exception e){
            System.out.println("未创建成功");
        }
    }
    /**
     * URLConnection对象操作get请求
     * 1.设置URLConnection的参数和普通请求属性
     * 2.建立实际连接
     * */
    public void get() throws IOException{
        //设置通用的请求属性
        urlConnection.setRequestProperty("accept", "*/*");
        urlConnection.setRequestProperty("connection", "Keep-Alive");
        urlConnection.setRequestProperty("user-agent","Mozilla/4.0 (compatible; MSIT 6.0; Windows NT 5.1; SV1)");
        
        //建立实际连接
        urlConnection.connect();
        
        //获取响应资源
        response();
    }
    
    /**
     * URLConnection对象操作post请求
     * 1.设置URLConnection的参数和普通请求属性
     * 2.通过输出流来发送请求参数
     * */
    public void post(String param){
        //设置通用的请求属性
        urlConnection.setRequestProperty("accept", "*/*");
        urlConnection.setRequestProperty("connection", "Keep-Alive");
        urlConnection.setRequestProperty("user-agent","Mozilla/4.0 (compatible; MSIT 6.0; Windows NT 5.1; SV1)");
        
        //通过输出流来发送请求参数
        urlConnection.setDoOutput(true);urlConnection.setDoInput(true);
        try {
            PrintWriter printWriter = new PrintWriter(urlConnection.getOutputStream());
            printWriter.print(param);
            printWriter.flush();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        
        response();
    }
    
    /**
     * 读取请求后的响应内容
     * */
    public void response(){
        Map<String, List<String>> map = urlConnection.getHeaderFields();
        for(String key:map.keySet()){
            System.out.println(key+"---->"+map.get(key));
        }
        try {
            BufferedReader in = new BufferedReader(new InputStreamReader(urlConnection.getInputStream(),"utf-8"));
            String result = null;
            while(in.readLine() != null){
                result +="
"+in.readLine();
            }
            System.out.println(result);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            System.out.println("请求出现异常");
            e.printStackTrace();
        }
    }
}

public class Net {
    /**
     * 使用InetAddress类代表IP地址
     * InetAddress本身没有太多的功能,它代表一个IP地址对象,后期会大量用到该类
     * @throws Exception 
     * */
    public void inetAddress() throws Exception{
        System.out.println("---------InetAddress---------");
        //根据主机名获取对应的InetAddress实例
        InetAddress inetAddress = InetAddress.getByName("www.hjlin.com");
        System.out.println(inetAddress);
        System.out.println("是否可抵达"+inetAddress.isReachable(5000));
        inetAddress = InetAddress.getByAddress(new byte[]{127,0,0,1});
        System.out.println(inetAddress);
        System.out.println(inetAddress.getCanonicalHostName());
    }
    
    /**
     * URLDecoder,将application/x-www-form-urlencoded MIME字符串转换为普通字符串
     * URLEncoder,将普通字符串转换为application/x-www-form-urlencoded MIME字符串
     * 用于url地址字符串编码 的转换
     * */
    public void coder() throws UnsupportedEncodingException{
        System.out.println("-------URLDecoder/URLEncoder-------");
        String keyWord = URLEncoder.encode("百度","UTF-8");
        System.out.println(keyWord);
        keyWord = URLDecoder.decode("%E7%99%BE%E5%BA%A6","UTF-8");
        System.out.println(keyWord);
    }
    
    /**
     * URL,代表统一资源定位器
     * URL可以由:协议名,主机,端口,资源名组成,例如:http://www.hjlin.com/index.html
     * */
    public void url() throws Exception{
        System.out.println("--------url--------");
        URL url = new URL("https://www.baidu.com");
        System.out.println("获取url协议名:"+url.getProtocol());
        System.out.println("获取url主机名:"+url.getHost());
        System.out.println("获取url端口:"+url.getPort());
        System.out.println("获取url资源"+url.getFile());
        System.out.println("获取url路径"+url.getPath());
        System.out.println("获取url查询字符部分"+url.getQuery());
        //打开URL返回InputStream资源
//        InputStream ins = url.openStream();
//        byte[] b = new byte[1024];
//        while(ins.read(b)>0){
//            System.out.println(new String(b));
//        }
//        ins.close();
    }
    
    public static void main(String[] args){
        try{
//            Net net = new Net();
//            net.inetAddress();
//            net.coder();
//            net.url();
            String path = "https://www.cnblogs.com/hjlin/";
            String param = "1=1";
            UrlConnection urlConnection = new UrlConnection(path+"?"+param);
//            urlConnection.get();
            path = "www.cnblogs.com";
            urlConnection.setUrlAndUrlConnection(path);
            urlConnection.post(param);
        }catch(Exception e){}
    }
}
View Code
原文地址:https://www.cnblogs.com/hjlin/p/11406690.html