package socketTest;
import java.io.*;
import java.util.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.net.*;
public class HttpIEDemo {
/**
* 需求:
* 1:服务器是tomcat,里面有一个hello.html简单的页面
* 2:客户端自定义
* 要求自定义的客户端能访问服务器的资源
*
* 简易版 IE 浏览器 1.0
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
MyIeWeb ie = new MyIeWeb();
}
}
class MyIeWeb extends JFrame implements ActionListener
{
private TextField tf = null;
static public TextArea ta = null;
private JButton jb1 = null;
private JPanel jp1 = null;
private JPanel jp2 = null;
//初始化相关的组件及注册简听
public MyIeWeb()
{
tf = new TextField(70);
ta = new TextArea();
jb1 = new JButton("转到");
jb1.addActionListener(this);
jb1.setActionCommand("zd");
jp1 = new JPanel();
jp2 = new JPanel();
jp1.add(tf);
jp1.add(jb1);
jp2.add(ta);
this.setLayout(new BorderLayout());
this.add(jp1,BorderLayout.NORTH);
this.add(jp2,BorderLayout.CENTER);
this.setSize(700,300);
this.setLocation(400,300);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setVisible(true);
}
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
if (e.getActionCommand().equals("zd"))
{
//监听处理
showIEWeb();
}
}
public void showIEWeb()
{
// System.out.println("转到");
//每一次访问前要刷新
ta.setText("");
//得到url的值
String url = tf.getText(); //http://192.168.1.154:8888/MyWebSit/hello.html
//分割得到 ip port path
int index1 = url.indexOf("//")+2;
int index2 = url.indexOf("/",index1);
String str = url.substring(index1, index2);
String []arr = str.split(":");
String ip = arr[0];
int port = Integer.parseInt(arr[1]);
String Path = url.substring(index2);
try {
Socket s = new Socket(ip, port);
SocketGet sg = new SocketGet(s);
sg.get(Path);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
class SocketGet
{
private Socket s;
PrintWriter pw;
public SocketGet(Socket s)
{
this.s = s;
}
void get(String Path)
{
try {
//向服务器发请求
pw = new PrintWriter(s.getOutputStream(),true);
pw.println("GET "+Path+" HTTP/1.1");
pw.println("Accept: */*");
pw.println("Accept-Language: zh-CN");
pw.println("Accept-Encoding: gzip, deflate");
pw.println("Host: 192.168.1.154:8888");
pw.println("Connection: closed");
pw.println();
pw.println();
BufferedReader bufr = new BufferedReader(new InputStreamReader(s.getInputStream()));
String len=null;
while ((len=(bufr.readLine())) != null)
{
//写到面板上
MyIeWeb.ta.append(len+"\r\n");
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally{
try {
//关闭资源
s.close();
pw.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}