gpt4 book ai didi

java - NanoHTTPD 如何从应用程序呈现变量

转载 作者:行者123 更新时间:2023-11-27 23:48:48 26 4
gpt4 key购买 nike

我玩的是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 文件并在浏览器中显示?

最佳答案

您必须从磁盘读取模板,并将 [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);
}
}

有关更多高级示例,请查看 Samples package NanoHttpd Github 站点。

关于java - NanoHTTPD 如何从应用程序呈现变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28341986/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com