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

时间:2016-09-03 15:32:59

标签: java http webserver

首先创建了Web服务器:

主要方法的代码

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();
    }
}

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

1 个答案:

答案 0 :(得分:2)

发回302,添加带有所需网址的Location标题,浏览器为您完成所有工作,无需在代码中实现任何内容。