美文网首页
URL网络编程

URL网络编程

作者: 冯宏志 | 来源:发表于2021-02-21 23:31 被阅读0次

    URL类常用方法

    package java2;
    
    import java.net.MalformedURLException;
    import java.net.URL;
    
    public class URLTest {
        public static void main(String[] args) {
            URL url1 = null;
            try {
                url1 = new URL("https://www.bilibili.com/video/BV1Kb411W75N?p=586");
            } catch (MalformedURLException e) {
                e.printStackTrace();
            }
    //        public String getProtocol( ) 获取该URL的协议名
            System.out.println(url1.getProtocol());//https
    //        public String getHost( ) 获取该URL的主机名
            System.out.println(url1.getHost());//www.bilibili.com
    //        public String getPort( ) 获取该URL的端口号
            System.out.println(url1.getPort());//-1
    //        public String getPath( ) 获取该URL的文件路径
            System.out.println(url1.getPath());//  /video/BV1Kb411W75N
    //        public String getFile( ) 获取该URL的文件名
            System.out.println(url1.getFile());//  /video/BV1Kb411W75N?p=586
    //        public String getQuery( ) 获取该URL的查询名
            System.out.println(url1.getQuery());//p=586
        }
    }
    
    

    URL编程:从网络上下载一张图片到本地

    package java2;
    
    import javax.net.ssl.HttpsURLConnection;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.net.URL;
    
    public class URLTest1 {
        public static void main(String[] args) {
            HttpsURLConnection urlConnection = null;
            InputStream is = null;
            FileOutputStream fos = null;
            try {
                URL url = new URL("https://ss3.bdstatic.com/70cFv8Sh_Q1YnxGkpoWK1HF6hhy/it/u=2271518174,2892241511&fm=11&gp=0.jpg");
    
                urlConnection = (HttpsURLConnection) url.openConnection();
    
                urlConnection.connect();
    
                is = urlConnection.getInputStream();
                fos = new FileOutputStream("day09\\百度图片.jpg");
                byte[] buffer = new byte[1024];
                int len;
                while ((len = is.read(buffer)) != -1){
                    fos.write(buffer,0,len);
                }
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if (fos != null)
                    try {
                        fos.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                if (is != null)
                    try {
                        is.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                if (urlConnection != null)
                    urlConnection.disconnect();
            }
        }
    }
    
    
    下载到的图片

    相关文章

      网友评论

          本文标题:URL网络编程

          本文链接:https://www.haomeiwen.com/subject/ertggktx.html