首先创建网络服务器:
主要方法的代码
HttpServer server = null;
try {
server = HttpServer.create(new InetSocketAddress(9000), 0);
} catch (IOException ex) {
}
server.createContext("/", new MyHandler());
server.setExecutor(null);
server.start();
Run Code Online (Sandbox Code Playgroud)
在同一个类中,我创建了 Myhandelr 类,以便将所有 GET 请求重定向到 google.com 或任何网站。
static class MyHandler implements HttpHandler {
@Override
public void handle(HttpExchange t) throws IOException {
String response = "This is the response";
boolean redirect=false;
if(t.getRequestMethod().equalsIgnoreCase("GET")){
t.sendResponseHeaders(302, response.length());
HttpURLConnection conn = (HttpURLConnection) new URL("http://localhost:9000")
.openConnection();
int status = t.getResponseCode();
if (status != HttpURLConnection.HTTP_OK) {
if (status == HttpURLConnection.HTTP_MOVED_TEMP
|| status == …Run Code Online (Sandbox Code Playgroud)