以下是自定义的浏览器的可视化界面的代码,看红字部分,链接的Tomcat服务器,向服务器发送的消息头的小失误造成不能读取服务器返回的数据,一个小小的疏忽,纠结了很久,希望大家不要学我哦
虽然不是什么大问题,但是这说明了一个道理--编程是马虎不得的
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.net.*;
public class MyGUIIE{
private Frame fra;
private Button but;
private TextField tf;
private TextArea ta;
private Dialog d;
private Button but1;
private Label la;
public static void main(String[] args) {
// TODO Auto-generated method stub
new MyGUIIE().Init();
}
public void MyEvent(){
but.addActionListener(new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
try {
show();
} catch (UnknownHostException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
});
fra.addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e){
System.exit(0);
}
});
d.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e){
d.setVisible(false);
}
});
but1.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
d.setVisible(false);
}
});
}
public void show() throws UnknownHostException, IOException{
ta.setText("");
String url=tf.getText();
int index1=url.indexOf("//")+2;
int index2=url.indexOf("/",index1);
String hostport=url.substring(index1, index2); //http://localhost:8080/myIE/a.html
String[] buf=hostport.split(":");
String host=buf[0];
int port=Integer.parseInt(buf[1]);
String path=url.substring(index2);
Socket s=new Socket(host,port);
PrintWriter pw=new PrintWriter(s.getOutputStream(),true);
pw.println("GET "+path +" HTTP/1.1");//HTTP前面是有空格的,少了空格Tomcat服务器不识别
pw.println("Accept: */*");
pw.println("Accept-Language: zh-CN");
pw.println("Host:"+hostport);
pw.println("Connection: Keep-Alive");
pw.println();
pw.println();
InputStream in=s.getInputStream();
byte[] arr=new byte[1024];
int len=0;
len = in.read(arr);
ta.append(new String(arr,0,len));
s.close();
}
public void DiaMethod(){
d=new Dialog(fra, "错误提示",true);
d.setLayout(new FlowLayout());
d.setBounds(300,150,200,100);
la=new Label();
but1=new Button("确定");
String error=new String("输入错误,请检查后重新输入");
la.setText(error);
d.add(la);
d.add(but1);
}
public void Init(){
fra=new Frame("我的GUI 1号");
fra.setBounds(500, 100, 600, 400);
fra.setLayout(new FlowLayout());
tf=new TextField(55);
fra.add(tf);
but=new Button("转到");
fra.add(but);
ta=new TextArea(20,65);
fra.add(ta);
DiaMethod();
MyEvent();
fra.setVisible(true);
}
}
|
|