---
title: "java URLConnection "
author: "bcworld"
date: "2012-05-27T13:36:06Z"
tags: []
categories: ["编程语言"]
slug: "java-urlconnection"
draft: false
lastmod: "2012-05-26T21:13:26Z"
id: 1541929
url: "https://bcworld.iteye.com/blog/1541929"
---

```
package net;
import java.net.*;
import java.io.*;
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class GetHtml {
	public static void main(String[] args) {
		new DownNetFile();
	}
}
class DownNetFile extends JFrame implements ActionListener{
	JTextField inField=new JTextField(30);
	JTextArea show=new JTextArea();
	JButton button=new JButton("Open");
	JPanel panel=new JPanel();
	JLabel label=new JLabel("URL:");;
	public DownNetFile(){
		super("读取HTML文件");
		
		Container con=this.getContentPane();
		//panel
		panel.add(label);
		panel.add(inField);
		panel.add(button);
		//jsp
		JScrollPane jsp=new JScrollPane(show);
		//con
		con.add(panel,BorderLayout.NORTH);
		con.add(jsp);
		//注册监听
		button.addActionListener(this);
		inField.addActionListener(this);
		this.setDefaultCloseOperation(EXIT_ON_CLOSE);
		this.setVisible(true);
		this.setSize(500,400);
	}
	
	public void actionPerformed(ActionEvent e) {
		this.readByURL(inField.getText().trim());
		
	}
	public void readByURL(String urlName){
		try {
			URL url=new URL(urlName);
			URLConnection tc=url.openConnection();
			tc.connect();
			InputStreamReader in=new InputStreamReader(tc.getInputStream());
			BufferedReader br=new BufferedReader(in);
			String inLine=null;
			while((inLine=br.readLine())!=null){
				show.append(inLine+'\n');
			}
			br.close();	
			
		} catch (Exception e) {
			e.printStackTrace();
		}	
	}
}
```

 

    ![](http://dl.iteye.com/upload/attachment/0068/7021/b0399480-03ec-3963-b68f-d29978f6e6e7.png)