Redirect to another domain from nanoHttpd server
Asked Answered
T

1

5

I have implemented nanohttpd server nano My goal is to forward request to different domain based on condition i have.

My code is like this

package CreateServer;

import java.io.File;
import java.io.IOException;
import java.util.Collections;
import java.util.Iterator;
import java.util.Map;
import java.util.Properties;

import fi.iki.elonen.NanoHTTPD;

import javax.xml.ws.Response;

public class App extends NanoHTTPD {

    public App() throws IOException {
        super(8080);
        start(NanoHTTPD.SOCKET_READ_TIMEOUT, false);
        System.out.println("\nRunning! Point your browers to http://localhost:8080/ \n");
        
    }

    public static void main(String[] args) {
        try {
            new App();
        } catch (IOException ioe) {
            System.err.println("Couldn't start server:\n" + ioe);
        }
    }

    @Override
    public Response serve(IHTTPSession session) {
        String msg = "<html><body><h1>Hello server</h1>\n";
        Map<String, String> parms = session.getParms();
        if (parms.get("username") == null) {
            msg += "<form action='?' method='get'>\n  <p>Your name: <input type='text' name='username'></p>\n" + "</form>\n";
        } else {
            msg += "<p>Hello, " + parms.get("username") + "!</p>";
        }
        String websiteName="https://www.google.com";
        StringBuilder html=new StringBuilder();
        html.append("<html><head><meta http-equiv=\"refresh\" content=\"0; URL='"+websiteName+"'\" /></head>");
        html.append("<body></body></html>\n");

       // return new Response(Response.Status.OK, MIME_PLAINTEXT, null, 0);
        return newFixedLengthResponse(msg + "</body></html>\n");
       // return newFixedLengthResponse(html.toString());
      //  Response response=new Response(Response.IStatus.class.);
       // response.sendRedirect("login.jsp");

        //return Response()
    }

}

The problem is whenever i try to redirect to another domain

It rediects to https://www.google.com

But it rediect to www.google.comfrom client side .But is there any correct way to send request to server side other than client side ?????

How can i do this ?Is their other way to do this? Please help.

Tamera answered 27/6, 2016 at 15:36 Comment(0)
T
9

In the sample below when user tries to open your site.com/redirectme it will be redirected to the google.

@Override
public Response serve(IHTTPSession session) {

    switch (session.getUri()) {

        case "/redirectme":

            Response r = newFixedLengthResponse(Response.Status.REDIRECT, MIME_HTML, "");
            r.addHeader("Location", "http://google.com");
            return r;
        default:
            return super.serve(session);
}
Thirion answered 20/3, 2017 at 17:29 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.