Pass Parameters from Simple Function to a Private Class?

I am doing some work with the sunhttpserver.

Here is the java (extract) that starts the server and displays Hello World.

java
@SimpleFunction
  public void StartServer(String path, int port) throws IOException {
    try {
    server = HttpServer.create(new InetSocketAddress("0.0.0.0", port), 0);
    server.createContext(path, new MyHandler());
    server.setExecutor(null);
    server.start();
    } catch (IOException e){
      Log.e("SUNServer", e.toString());
    }
  }

  private class MyHandler implements HttpHandler {
    public void handle(HttpExchange t) throws IOException {
      InputStream is = t.getRequestBody();
      is.read(); // .. read the request body
      String response = "Hello World";
      t.sendResponseHeaders(200, response.length());
      OutputStream os = t.getResponseBody();
      os.write(response.getBytes());
      os.close();
    }

I would like to be able to include some more parameters in the SimpleFunction that can get passed to the private class

image

(as you can see to input in the simplefunction (1) and pass through MyHandler() to the private class (2)

For example to be able to change the message Hello World. I may have other parameters as well that need to be changed in a more expansive version of the handler class. Looks like `handle() will accept parameters, but how to get them in there from the function ?

Any suggestions ?

Since you are creating an implementation of the HttpHandler class you could modify the constructors to accept the arguments you prefer.

It would be something like

private class MyHandler implements HttpHandler {

    // nested variables

    private final String path;
    private final int port;

    public MyHandler(String path, int port) {
        this.path = path;
        this.port = port;
    }

    public void handle(HttpExchange t) throws IOException {
      InputStream is = t.getRequestBody();
      is.read(); // .. read the request body
      String response = "Hello World";
      t.sendResponseHeaders(200, response.length());
      OutputStream os = t.getResponseBody();
      os.write(response.getBytes());
      os.close();
    }

I have just typed the code, you maybe required to call the super() function if the IDE shows redlines.

2 Likes

Anyways, the HttpHandler class is a part of javax package, I'm not sure if they are present in Android.

Yay, this works:

image
image

image

1 Like

ζœŸεΎ…ζ–°ζ‰©ε±• :grinning:

1 Like

You can "feed" the msg with the content of an html file, and the server will render it

image

1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.