我正在尝试在JavaFX WebView中加载localhost网站,但它似乎不起作用。我在加载网页之前在应用程序中创建HttpServer,但它只显示一个空白屏幕。导航到谷歌浏览器中的http://localhost:8080/index.html是有效的,因此我猜测WebView试图加载它一定是个问题。加载其他非本地主机页面确实有效,但我无法弄清楚为什么本地主机页面有问题。
下面的代码首先创建带有本地html文件的HttpServer,然后继续创建JavaFX阶段并将localhost站点加载到WebView中,只显示空白页。
public class Main extends Application {
static String path = "";
static HashMap<String, String> pages = new HashMap();
public static void main(String[] args) throws Exception {
HttpServer server = HttpServer.create(new InetSocketAddress(8080), 0);
createPage(server, "/index.html", "index.html");
server.setExecutor(null);
server.start();
launch(args);
}
public void start(Stage stage) throws Exception {
try {
WebView webview = new WebView();
webview.getEngine().load(
"http://127.0.0.1:8080/index.html"
);
webview.setPrefSize(640, 390);
stage.setScene(new Scene(webview));
stage.show();
}catch (Exception e){
e.printStackTrace();
}
}
static class MyHandler implements HttpHandler {
@Override
public void handle(HttpExchange t) throws IOException {
try {
String response = readFile(pages.get(t.getHttpContext().getPath()), Charset.defaultCharset());
t.sendResponseHeaders(200, response.length());
OutputStream os = t.getResponseBody();
os.write(response.getBytes());
os.close();
}catch (Exception e){
e.printStackTrace();
}
}
}
static void createPage(HttpServer server, String context, String path){
pages.put(context, path);
server.createContext(context, new MyHandler());
}
static String readFile(String path, Charset encoding)
throws IOException
{
byte[] encoded = Files.readAllBytes(Paths.get(path));
return new String(encoded, encoding);
}
}
非常感谢任何尝试解决此问题的帮助。谢谢!
答案 0 :(得分:0)
更改t.sendResponseHeaders(200,response.length()); to t.sendResponseHeaders(200,0);似乎为我解决了这个问题。