网络编程3-URL编程(URL)

1、URL(Uniform Resource Locatior) 统一资源占位符,表示Intenet上某一资源的地址

2、URL的组成部分

传输协议:主机名:端口号:文件名

例:http://192.168.1.151:10085/webapp/js/service.js

3、URL的openStream()方法可以开启输入流

输出则要考URL的openConnection获取URLConnection对象

4、例子,注释

package com.url.test;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

import org.junit.Test;

public class TestURL {
    
    @Test
    public void urlTest(){
        //1、创建url对象
        URL url = null;
        try {
            url = new URL("http://127.0.0.1:8080/test/hello.txt?a=1&b=2");
        } catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        //获取协议名
        System.out.println(url.getProtocol());
        //获取主机名
        System.out.println(url.getHost());
        //获取端口号
        System.out.println(url.getPort());
        //获取文件路径
        System.out.println(url.getPath());
        //获取文件名
        System.out.println(url.getFile());
        //文件相对位置
        System.out.println(url.getRef());
        //参数
        System.out.println(url.getQuery());
        
        
        //2、把服务器资源读进来
        InputStream is = null;
        try {
            is = url.openStream();
            byte [] b = new byte[20];
            int len;
            while((len = is.read(b)) != -1){
                System.out.println(new String(b,0,len));
            }
            
            is.close();
        } catch (IOException e) {
            e.printStackTrace();
        }finally{
            if(is != null){
                try {
                    is.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
        
        
        //3、写出去,注意先获取URLConnetcion对象
        OutputStream os = null;
        try {
            URLConnection urlConn = url.openConnection();
            os = urlConn.getOutputStream();
            os.write("Hello ".getBytes());
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }finally{
            if(os != null){
                try {
                    os.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
        
        
        
    }
}
原文地址:https://www.cnblogs.com/fubaizhaizhuren/p/5060033.html