[英]JavaFX WebView won't load localhost website
我正在嘗試在JavaFX WebView中加載本地主機網站,但是它似乎無法正常工作。 在加載網頁之前,我正在應用程序中創建HttpServer,但是它僅顯示空白屏幕。 在Google Chrome瀏覽器中導航至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);
}
}
感謝您為解決此問題提供的任何幫助。 謝謝!
更改t.sendResponseHeaders(200,response.length()); 到t.sendResponseHeaders(200,0); 似乎為我解決了這個問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.