各位JAVA同僚,本人想使用Socket来得到一个WEB页面内容.原代码如下:
import java.io.*;
import java.net.Socket;public class SocketTest{
private Socket socket;
private BufferedReader reader;
private BufferedWriter writer;
public void init() throws IOException{
String host="www.tsinghua.edu.cn";//此处为主机地址
int port=80;
socket=new Socket(host,port);
reader=new BufferedReader(new InputStreamReader(socket.getInputStream()));
writer=new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
}
public void connect() throws IOException{
String buff=null;
write("GET /index.html\n");
while((buff=reader.readLine())!=null)
process(buff);
}
public void process(String msg){
System.out.println(msg);
}
public void write(String msg){
try{
writer.write(msg);
writer.flush();
}catch(IOException e){
System.err.println("Write failed:"+e.getMessage());
}
}
public void destroy(){
try{
if(reader!=null) reader.close();
if(writer!=null) writer.close();
if(socket!=null) socket.close();
}catch(IOException e){
}
}
public static void main(String[] args){
SocketTest test=new SocketTest();
try{
test.init();
test.connect();
}catch(IOException e){
System.err.println("Failed:"+e.getMessage());
}finally{
test.destroy();
}
}
}
这个程序能正常运行,但是主机地址改成其他地址,如www.baidu.com就行不通了,要么找不到页面,又么没有什么显示!!!请大家帮帮忙!
import java.io.*;
import java.net.Socket;public class SocketTest{
private Socket socket;
private BufferedReader reader;
private BufferedWriter writer;
public void init() throws IOException{
String host="www.tsinghua.edu.cn";//此处为主机地址
int port=80;
socket=new Socket(host,port);
reader=new BufferedReader(new InputStreamReader(socket.getInputStream()));
writer=new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
}
public void connect() throws IOException{
String buff=null;
write("GET /index.html\n");
while((buff=reader.readLine())!=null)
process(buff);
}
public void process(String msg){
System.out.println(msg);
}
public void write(String msg){
try{
writer.write(msg);
writer.flush();
}catch(IOException e){
System.err.println("Write failed:"+e.getMessage());
}
}
public void destroy(){
try{
if(reader!=null) reader.close();
if(writer!=null) writer.close();
if(socket!=null) socket.close();
}catch(IOException e){
}
}
public static void main(String[] args){
SocketTest test=new SocketTest();
try{
test.init();
test.connect();
}catch(IOException e){
System.err.println("Failed:"+e.getMessage());
}finally{
test.destroy();
}
}
}
这个程序能正常运行,但是主机地址改成其他地址,如www.baidu.com就行不通了,要么找不到页面,又么没有什么显示!!!请大家帮帮忙!
原来问题是出在这里
public void connect() throws IOException{
String buff=null;
write("GET /index.html\n");//问题出在这里,把字符串改为GET / HTTP/1.0\r\n\r\n
while((buff=reader.readLine())!=null)
process(buff);
}
修改之后就没问题了,至于为什么改成这样后就没出现问题,而不改之前对www.tsinghua.edu.cn为什么还能正确运行,其中的原理就搞不清楚了,但还是谢谢大家!
www.tsinghua.edu.cn的web服务器软件支持“GET ... \n”的请求
但这不是规范的HTTP请求规范的请求应该是所有请求之后再换一行,因此最后一条请求语句后要换两行
GET ... \n\n
或
GET ... \r\n\r\n