网络编程之解析网页

来源:互联网 发布:淘宝的等级怎么升级快 编辑:程序博客网 时间:2024/06/03 19:21
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(); }}  


 
原创粉丝点击