URL的全名叫做对统一资源定位符(Uniform Resource Locator)的抽象,其实就好像现在中的身份证号一样的,可以通过这一串字符找到自己想要去找的地方;
URL url=new URL(www.baidu.com);创建一个百度的URL
Internet是用于获取主机信息
有两个实例方法
getHostName()用来获取InetAddress对象所含的域名。
gethostAddress()获取InetAddress对象的IP地址
//显示网络的文档内容
import java.awt.*;
import java.awt.event.*;
import java.net.*;
import java.io.*;
import javax.swing.JEditorPane;
public class Example11_2
{
public static void main(String args[])
{
new Win();
}
}
class Win extends Frame implements ActionListener,Runnable
{
Button button;
URL url;
TextField text;
JEditorPane editpane;
byte b[]=new byte[118];
Thread thread;
public Win()
{
text=new TextField(20);
editpane=new JEditorPane();
editpane.setEditable(false);
button=new Button("确定");
button.addActionListener(this);
thread=new Thread(this);
Panel p=new Panel();
p.add(new Label("输入网址:"));
p.add(text);
p.add(button);
ScrollPane scroll=new ScrollPane();
scroll.add(editpane);
add(scroll,BorderLayout.CENTER);
add(p,BorderLayout.NORTH);
setBounds(160,60,360,300);
setVisible(true);
validate();
addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
});
}
public void actionPerformed(ActionEvent e)
{
if(!(thread.isAlive()))
{
thread=new Thread(this);
try{thread.start();}
catch(Exception ee)
{text.setText("我正在读取"+url);
}
}
}
public void run()
{
try{
editpane.setText(null);
url=new URL(text.getText().trim());
editpane.setPage(url);
}
catch(Exception e1)
{
text.setText(""+e1);
return;
}
}
}
史上最差的模拟网页浏览器代码
import java.awt.*;
import java.awt.event.*;
import java.net.*;
import java.io.*;
import javax.swing.event.*;
import javax.swing.*;
public class Example11_3
{
public static void main(String args[])
{
new LinkWin();
}
}
class LinkWin extends JFrame implements ActionListener,Runnable
{
Button button;
URL url;
TextField text;
JEditorPane editpane;
byte b[]=new byte[118];
Thread thread;
public LinkWin()
{
text=new TextField(20);
editpane=new JEditorPane();
editpane.setEditable(false);
button=new Button("确定");
button.addActionListener(this);
thread=new Thread(this);
Panel p=new Panel();
p.add(new Label("输入网址"));
p.add(text);
p.add(button);
ScrollPane scroll=new ScrollPane();
scroll.add(editpane);
add(scroll,BorderLayout.CENTER);
add(p,BorderLayout.NORTH);
setBounds(60,60,360,300);
setVisible(true);
validate();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
editpane.addHyperlinkListener(new HyperlinkListener()
{
public void hyperlinkUpdate(HyperlinkEvent e)
{
if(e.getEventType()==HyperlinkEvent.EventType.ACTIVATED)
{
try{
editpane.setPage(e.getURL());
}catch(IOException e1)
{
editpane.setText(""+e1);
}
}
}
});
}
public void actionPerformed(ActionEvent e)
{
if(!(thread.isAlive()))
thread=new Thread(this);
try{thread.start();}catch(Exception ee){text.setText("我正在读取"+url);}
}
public void run()
{
try{
editpane.setText(null);
url=new URL(text.getText().trim());
editpane.setPage(url);
}catch(Exception e1)
{
text.setText(""+e1);
return;
}
}
}