What is a URL? And URL class and urlconnection class

URL concept

protocol://resourceName
http://www.sun.com/    协议名://主机名
http://localhost:8080/Test/admin/login.jsp 协议名://机器名:端口号/文件名

URL class

Urlconnection class

Example 1

package ch16;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
public class URLDemo
{
    public static void main(String[] args)
    {
        try
        {
            URL url=new URL("http://www.baidu.com/");
            System.out.println("协议:" + url.getProtocol());
            System.out.println("主机:" + url.getHost());
            System.out.println("端口:" + url.getPort());
            InputStream in;
        }
        catch(IOException e)
        {
            //TODO 自动生成的 catch 块
            e.printStackTrace();
        }
    }
}
URLConnection uc=url.openConnection();
in=uc.getInputStream();
byte[] b=new byte[1024];
int len;
while((len=in.read(b))!=-1)
{
    System.out.println(new String(b,len));
}
in.close();
协议:http
主机:www.baidu.com
端口:-1
<!DOCTYPE html>
<!--STATUS OK--><html> <head><Meta http-equiv=content-type content=text/html;charset=utf-8><Meta http-equiv=X-UA-Compatible content=IE=Edge><Meta content=always name=referrer><link rel=stylesheet type=text/css href=http://s1.bdstatic.com/r/www/cache/......<img src=//www.baidu.com/img/gs.gif> </p> </div> </div> </div> </body> </html>

Extract URL protocol name

package ch16;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Scanner;
public class URLDemo1
{
    public static void main(String[] args)
    {
        try
        {
            Scanner scan=new Scanner(system.in);    //创建输入扫描器
            System.out.println("请输入一个完整的网址:");
            String line=scan.nextLine();    //获取用户输入文本
            URL url=new URL(line);    //创建URL对象
            System.out.println("这个网址的主机名称是:"+url.getHost());    //获取主机名称
            System.out.println("这个网址的URL协议名称是:"+url.getProtocol());    //获取协议名称
        }
        catch(MalformedURLException e)
        {
            System.out.println("输入的是非法网址");    //提示错误信息
        }
    }
}
请输入一个完整的网址:
http://www.baidu.com
这个网址的主机名称是:www.baidu.com
这个网址的URL协议名称是:http
请输入一个完整的网址:
ftp://www.baidu.com/SEO
这个网址的主机名称是:www.baidu.com
这个网址的URL协议名称是:ftp
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>