大可制作:QQ群:31564239(asp|jsp|php|mysql)

Java Gossip: HTTP 重定向

如果您的网站移站了,而您只是要作一个重定向的动作,则可以撰写一个可以丢出重定向标头的简单服务器,当浏览器接收到重定向标头时,会重定向您指定的网站。

HTTP 协定中,重定向标头是由Location: 控制,这个标头需浏览器支持HTTP/1.0以上才有作用,所以最好再指定一个备用的HTML网页,如果使用者的浏览器不支持HTTP/1.0以上,可以直接显示HTML网页告知讯息,例如:
  • moved.html
<html> 
<head>
</head>
<body>
This site has been moved to: http://caterpillar.onlyfun.net
</body>
</html>

下面这个程序可以让浏览器重定向至指定的网址,您可以自行指定连接埠、重定向网页与重定向网址:
  • HttpRedirectServer.java
package onlyfun.caterpillar;

import java.io.*;
import java.net.*;

public class HttpRedirectServer {
public static void main(String[] args) {
int port = Integer.parseInt(args[0]);
String movedHtml = args[1];
String redirectUrl = args[2];

try {
System.out.println("HTTP 重定向...");
ServerSocket serverSkt = new ServerSocket(port);

while(true) {
System.out.printf("倾听连线于 %d ...%n", port);
Socket clientSkt = serverSkt.accept();
System.out.printf("%s 连线....",
clientSkt.getInetAddress().toString());

PrintStream printStream =
new PrintStream(clientSkt.getOutputStream());

BufferedReader protocolReader =
new BufferedReader(
new InputStreamReader(
clientSkt.getInputStream()));

String readin = protocolReader.readLine();
String[] tokens = readin.split("[ \t]");


// 是否支持HTTP/1.0以上
if(tokens.length >= 3 && tokens[2].startsWith("HTTP/")) {
while(true) {
if(protocolReader.readLine().trim().equals("")) {
break; // 空白行,接下来header部份,不处理
}
}

// 送出 HTTP header
printStream.print("HTTP/1.0 302 FOUND\r\n");
printStream.print(
"Date: " + (new java.util.Date()) + "\r\n");
printStream.print("Server: httpRedirect v0.1\r\n");
printStream.print("Location: " + redirectUrl + "\r\n");
printStream.print("Content-type: text/html\r\n\r\n");
}
else {
BufferedReader reader =
new BufferedReader(
new FileReader(movedHtml));

String htmlContent = null;
while((htmlContent = reader.readLine()) != null) {
printStream.println(htmlContent);
}
reader.close();
}

printStream.flush();
clientSkt.close();
}
}
catch(IOException e) {
e.printStackTrace();
}
}
}

服务器只会显示客户连线端的IP位址,可以在客户端使用Telnet来测试看看结果:
$ telnet localhost 80
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
GET / HTTP/1.0

HTTP/1.0 302 FOUND
Date: Wed Jul 16 01:06:55 CST 2003
Server: httpRedirect v0.1
Location: http://www.caterpillar.onlyfun.net/phpBB2/
Content-type: text/html

Connection closed by foreign host.

$ telnet localhost 80
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
GET /
<html>
<head>
</head>
<body>
This site has been moved to: http://caterpillar.onlyfun.net
</body>
</html>
Connection closed by foreign host.