New Dev New Dev - 1 month ago 4x
HTTP Question

I want to write a Java program to redirect all GET requests from a browser to a given URL using an HTTP 302 response message to the browser

First created the web server:

Code for the main method

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

server.createContext("/", new MyHandler());

in the same class I created Myhandelr class In order to redirect all GETs request to or any website.

static class MyHandler implements HttpHandler {
public void handle(HttpExchange t) throws IOException {
String response = "This is the response";
boolean redirect=false;
t.sendResponseHeaders(302, response.length());
HttpURLConnection conn = (HttpURLConnection) new URL("http://localhost:9000")
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 ="";
conn = (HttpURLConnection) new URL(newUrl).openConnection();
System.out.println("Redirect to URL : " + newUrl);
t.sendResponseHeaders(200, response.length());
OutputStream os = t.getResponseBody();


I have no idea what i did Wrong, also I'm not sure if this the best way to do it.


Send back a 302, add a Location header with the required URL and the browser does all the work for you, there's no need to implement anything in your code.