java - 我想编写一个 Java 程序,使用发送给浏览器的 HTTP 302 响应消息将所有 GET 请求从浏览器重定向到给定的 URL

标签 java http webserver

首先创建网络服务器:

主要方法的代码

HttpServer server = null;
try {
    server = HttpServer.create(new InetSocketAddress(9000), 0);
} catch (IOException ex) {

}
server.createContext("/", new MyHandler());
server.setExecutor(null);
server.start();

在同一个类中,我创建了 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 == HttpURLConnection.HTTP_MOVED_PERM
                    || status == HttpURLConnection.HTTP_SEE_OTHER)
                    redirect = true;
            }
            if (redirect) {
                String newUrl ="http://www.google.com";
                conn = (HttpURLConnection) new URL(newUrl).openConnection();
                System.out.println("Redirect to URL : " + newUrl);
            }
        }
        t.sendResponseHeaders(200, response.length());
        OutputStream os = t.getResponseBody();
        os.write(response.getBytes());

        os.close();
    }
}

我不知道我做错了什么,我也不确定这是否是最好的方法。

最佳答案

发回 302,添加包含所需 URL 的 Location header ,浏览器会为您完成所有工作,无需在代码中实现任何内容。

关于java - 我想编写一个 Java 程序,使用发送给浏览器的 HTTP 302 响应消息将所有 GET 请求从浏览器重定向到给定的 URL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39308564/

相关文章:

java - 在循环中使用数组名称作为变量 (Java)

java - Android XML RSA,错误 : java. security.InvalidKeyException:传递给 RSA 的未知 key 类型

http - 什么是命名 cookie?

apache - 有没有一种方法可以/是否可以在Apache htaccess中进行重写?

go - 无法在 Go Gorilla 服务器中提供静态文件

http - 实现 Webhooks 的服务器端

java - 在 Jform(GUI) 的 3 个组合框中显示来自 java DB 的日期字段

java - 'error: variable a might not have been initialized' 在这个 if 构造中真的有必要吗?

http - 在 Pharo 中发出 HTTP 请求并获取响应 header

json - JSON数组到JSON对象