JavaFX WebView не загружает локальный веб-сайт

Я пытаюсь загрузить локальный веб-сайт в JavaFX WebView, но, похоже, он не работает. Я создаю HttpServer в приложении перед загрузкой веб-страницы, но он показывает только пустой экран. Переход к http://localhost:8080/index.html в Google Chrome работает, так что я предполагаю, что это должна быть проблема с WebView, пытающимся загрузить его. Загрузка других страниц, не являющихся локальными, работает, но я не могу понять, почему возникают проблемы с локальными страницами.

Приведенный ниже код начинается с создания HttpServer с локальными html-файлами, а затем переходит к созданию этапа JavaFX и загрузке локального сайта в 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);
    }

}

Любая помощь в попытке решить эту проблему очень ценится. Спасибо!


person GamingTom    schedule 22.11.2015    source источник
comment
Может ли он загружать другие страницы?   -  person Bill    schedule 22.11.2015


Ответы (1)


Изменение t.sendResponseHeaders(200, response.length()); в t.sendResponseHeaders(200, 0); казалось, решил проблему для меня.

person GamingTom    schedule 22.11.2015