网络编程之解析网页

public class Ip{   
 public static void main(String[] args){
	 InetAddress myIp=null;
	 try{
		 myIp=InetAddress.getLocalHost();
	 }catch(UnknownHostException e){}
	 System.out.println(myIp);
 }
}  

下面是你输入一个网址可以解析该网址的代码,界面有点丑不过功能还是可以的
public class Ip extends JFrame{ 
 JPanel jp;
 JButton b1;
 JTextField jf;
 JLabel jl;
 JScrollPane scrollPane;
 JTextArea ja;
 public Ip(){//构造方法
	 jp=new JPanel();
	 b1=new JButton("解析网页");
	 b1.addActionListener(new ActionListener(){
		  public void actionPerformed(final ActionEvent e){
			  String address=jf.getText().trim();//获得输入的网站
			  Collection urlCollection=getURLConnection(address);//调用方法获得网页截对象
			  Iterator it=urlCollection.iterator();//迭代器
			  while(it.hasNext()){
				  ja.append((String)it.next()+"\n");
			  }
		  }
	 });
	 b1.setBounds(350,20,100,20);
	 jp.add(b1);
	 jl=new JLabel("载入网址");
	 jl.setBounds(20,20,80,20);
	 getContentPane().add(jl);
	 jf=new JTextField(200);
	 jf.setBounds(100,20,200,20);
	 getContentPane().add(jf);
	 getContentPane().add(b1);
	 ja=new JTextArea();
	 scrollPane=new JScrollPane(ja);
	 
	 //scrollPane.setBounds(200,200,200,200);
	 getContentPane().add(scrollPane,BorderLayout.CENTER);
	 setVisible(true);
	 setSize(600,600);
	 setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
 }
 public Collection<String>getURLConnection(String urlString){
	 URL url=null;
	 URLConnection conn=null;
	 Collection<String>urlCollection=new ArrayList<String>();//创建集合对象
	 try{
		 url=new URL(urlString);//创建url对象
		 conn=url.openConnection();//获得链接对象
		 conn.connect();//打开链接
		 InputStream is=conn.getInputStream();//获取留对象
		 InputStreamReader in=new InputStreamReader(is,"UTF-8");
		 BufferedReader br=new BufferedReader(in);//缓冲流对象
		 String nextLine=br.readLine();//读取信息解析网页
		 while(nextLine!=null){
			 urlCollection.add(nextLine);//解析网页所有内容到集合中
			 nextLine=br.readLine();//读取信息解析网页
		 }
		 
	 }catch(Exception ex){
		 ex.printStackTrace();
	 }
	 return urlCollection;
 }
 public static void main(String[] args){
	 new Ip();
 }
}  




                
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值