从nanoHttpd服务器

时间:2016-06-27 15:36:35

标签: java nanohttpd

我已经实施了nanohttpd服务器nano 我的目标是根据我的条件将请求转发到不同的域。

我的代码就像这样

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

}

问题是每当我尝试重定向到另一个域

它重定向到https://www.google.com

但是它从客户端重新发送到www.google.com。但是有没有正确的方法向客户端以外的服务器端发送请求?????

我怎么能这样做?他们的其他方式是这样做的吗?请帮忙。

1 个答案:

答案 0 :(得分:5)

在下面的示例中,当用户尝试打开您的site.com/redirectme时,它将被重定向到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);
}