2

我基于它玩 NanoHTTPD 和 WebServer。要更新我的代码(应用程序)中的任何对象,我可以使用 GET/POST 方法。但是如何创建动态页面?例如,我在光盘上有 html 页面,它应该显示当前温度:

<html>
  <head>
    <title>My page</title>
  </head>

  <body>

    <p style="text-align: center">Temperature: [temperature variable] </p>

  </body>

</html>

如何将“可变温度”从基于 NanoHTTPD 的应用程序传递到 html 文件并在浏览器中呈现?

4

1 回答 1

2

您必须从磁盘中读取模板,并将[temperature variable]子字符串替换为您要包含的值。

要读取文件,您可以使用Files该类:

byte[] data = Files.readAllBytes(Paths.get("mytemplpate.html"));
String templ = new String(data, StandardCharsets.UTF_8);

要插入您的温度:

double temperature = 22.3;
String html = templ.replace("[temperature variable]", Double.toString(temperature));

最后用 NanoHTTPD 将其作为响应发送:

return new NanoHTTPD.Response(html);

完整的程序:

前言:不处理异常,这只是为了演示目的。

public class TemperatureServer extends NanoHTTPD {
    // Loaded and cached html template
    private static String templ;

    // Value of this variable will be included and sent in the response
    private static double temperature;

    public TemperatureServer () {
        super(8080);
    }

    @Override
    public Response serve(IHTTPSession session) {
        String html = templ.replace("[temperature variable]",
            Double.toString(temperature));
        return new NanoHTTPD.Response(html);
    }

    public static void main(String[] args) throws Exception {
        byte[] data = Files.readAllBytes(Paths.get("mytemplpate.html"));
        templ = new String(data, StandardCharsets.UTF_8);

        ServerRunner.run(TemperatureServer.class);
    }
}

有关更高级的示例,请查看 NanoHttpd Github 站点的Samples 包

于 2015-02-05T10:59:04.287 回答