From Gossip@Openhome

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: https://openhome.cc
</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: https://openhome.cc/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: https://openhome.cc
</body>
</html>
Connection closed by foreign host.