以下代码,socket链接到www.sina.com 80端口,但是在发送头部请求里host写的是www.sina.com端口号为1,为什么同样可以读取到新浪发回来的response信息? 这个header里面host的端口号到底有什么作用?
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import java.io.*;public class HttpTest {
public static void main(String[] args) {
Socket s = null;
PrintWriter pw = null;
BufferedReader br = null;
try {
s = new Socket("www.sina.com",80);
pw = new PrintWriter(new OutputStreamWriter(s.getOutputStream()));
pw.println("GET / HTTP/1.1");
pw.println("Host:www.sina.com:1");
pw.println("Content-Type:text/html");
pw.println(""); pw.flush();
br = new BufferedReader(new InputStreamReader(s.getInputStream()));
String str = "";
while((str = br.readLine()) != null) {
System.out.println(str);
}
} catch (UnknownHostException e) {
System.out.println("unknown server");
e.printStackTrace();
} catch (IOException e) {
System.out.println("IO exception");
e.printStackTrace();
} finally {
try {
if (br != null) {
br.close();
br = null;
}
if (pw != null) {
pw.close();
pw = null;
}
if (s != null) {
s.close();
s = null;
}
} catch (IOException e) {
System.out.println("IO异常");
e.printStackTrace();
}
}
}
}
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import java.io.*;public class HttpTest {
public static void main(String[] args) {
Socket s = null;
PrintWriter pw = null;
BufferedReader br = null;
try {
s = new Socket("www.sina.com",80);
pw = new PrintWriter(new OutputStreamWriter(s.getOutputStream()));
pw.println("GET / HTTP/1.1");
pw.println("Host:www.sina.com:1");
pw.println("Content-Type:text/html");
pw.println(""); pw.flush();
br = new BufferedReader(new InputStreamReader(s.getInputStream()));
String str = "";
while((str = br.readLine()) != null) {
System.out.println(str);
}
} catch (UnknownHostException e) {
System.out.println("unknown server");
e.printStackTrace();
} catch (IOException e) {
System.out.println("IO exception");
e.printStackTrace();
} finally {
try {
if (br != null) {
br.close();
br = null;
}
if (pw != null) {
pw.close();
pw = null;
}
if (s != null) {
s.close();
s = null;
}
} catch (IOException e) {
System.out.println("IO异常");
e.printStackTrace();
}
}
}
}
只是http头写的不合规范而已...