0

Необходимо в webview отобразить сайт, который лежит в assets Я выяснил, что для работы скриптов необходимо реализовать локальный сервер. Используя этот локальный веб-сервер, я получаю ошибку ERR_NAME_NOT_RESOLVED.

WebViewLocalServer.Server server;
WebViewLocalServer webViewLocalServer;

@SuppressLint("SetJavaScriptEnabled")    
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    LocalWebView webView = findViewById(R.id.local_web_view);
    webView.setWebViewClient(new MyWebViewClient());
    webView.setWebChromeClient(new WebChromeClient());
    webView.getSettings().setJavaScriptEnabled(true);

    webViewLocalServer = webView.getWebViewLocalServer();

    //WebViewLocalServer.AssetsBuilder assetsBuilder = new WebViewLocalServer.AssetsBuilder();
    //User AssetsBuilder for assets or ResBuilder for res
    WebViewLocalServer.AssetsBuilder assetsBuilder = new WebViewLocalServer.AssetsBuilder()

            // The default domain is androidplatform.net, which is an unused domain
            .setDomain("androidTest.com")

            // www is the default path, ie 'ASSETS_FOLDER/www'"
            .setPathInAndroidLocation("www")

            // generate a random subdomain, this is the default.  You can also clear the subdomain by setSubDomain("") or clearSubDomain()"
            // NOTE : Remember that a random subdomain means that cookies and history will be lost on activity/app restart
            .setRandomSubDomain()

            // HTTP, HTTPS, and FILE are enabled by default
            .setProtocol(WebViewLocalServer.UrlProtocol.HTTP, false)


            // no Url virtual path is set by default
            //
            // NOTE : Remember, if you define a virtual path AND your website uses <base href>,
            // then you need to adjust <base href> to match whatever is here (example <base href="/testpath/">
            .setUrlVirtualPath("testpath");

    server = webViewLocalServer.createHost(assetsBuilder);

    Uri uri = server.getServerUri(WebViewLocalServer.UrlProtocol.HTTP, "index.html");

    webView.loadUrl(uri.toString());

}

class MyWebViewClient extends WebViewClient {

    // For Lollipop and above.
    @Override
    public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) {
        return webViewLocalServer.shouldInterceptRequest(request);
    }
}

Подскажите, где искать проблему.

1
  • "для работы скриптов необходимо реализовать локальный сервер" Если речь не о PHP-скриптах, а о Javascript, то никакой сервер ему не требуется. Если JS у вас не работает, то просто неверно указаны пути к скриптам (перепутаны локальный с глобальным).
    – T-igra
    20 мая 2018 в 18:41

1 ответ 1

1

Решение на основе https://github.com/oceantear/Nanohttpd-for-Android

    dependencies {
    implementation 'org.nanohttpd:nanohttpd:2.3.1'        
    }

MyHTTPD.java

public class MyHTTPD extends NanoHTTPD {

private static final String
        MIME_PLAINTEXT = "text/plain",
        MIME_HTML = "text/html",
        MIME_JS = "text/javascript",
        MIME_CSS = "text/css",
        MIME_PNG = "image/png",
        MIME_FONT = "application/font-woff",
        MIME_MPEG = "audio/mpeg",
        MIME_OGA = "audio/ogg";

public static final int PORT = 8080;

private Context context;

MyHTTPD(int port, Context context) {
    super(port);
    this.context = context;
}

@Override
public Response serve(IHTTPSession session) {

    String answer = "";
    String uri;
    uri = session.getUri();
    Log.d("goodi", "uri = " + uri);
    Log.d("goodi", "uri substring(1)= " + uri.substring(1));

    InputStream buffer;
    if (uri.equals("/")) {
        try {
            BufferedReader reader = null;
            try {
                reader = new BufferedReader(new InputStreamReader(context.getAssets().open("index.html")));
            } catch (IOException e) {
                e.printStackTrace();
            }

            String line;
            StringBuilder stringBuilder = new StringBuilder();
            if (reader != null) {
                while ((line = reader.readLine()) != null) {
                    //answer += line + "\n";
                    stringBuilder.append(line).append("\n");
                }
            }
            if (reader != null) {
                reader.close();
            }
            answer = stringBuilder.toString();

        } catch (IOException ioe) {
            Log.w("Httpd", ioe.toString());
        }
        return newFixedLengthResponse(Response.Status.OK, MIME_HTML, answer);

    } else if (uri.endsWith("js")) {

        Log.d("goodi", "it's javascript file");
        try {
            buffer = context.getAssets().open(uri.substring(1));
            try {
                BufferedReader reader;

                reader = new BufferedReader(new InputStreamReader(buffer));

                String line;
                StringBuilder stringBuilder = new StringBuilder();
                while ((line = reader.readLine()) != null) {
                    stringBuilder.append(line).append("\n");
                    // answer += line + "\n";
                }
                reader.close();
                answer = stringBuilder.toString();

            } catch (IOException ioe) {
                Log.w("Httpd", ioe.toString());
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return newFixedLengthResponse(Response.Status.OK, MIME_JS, answer);

    } else if (uri.endsWith("gif") || uri.endsWith("png")) {
        Log.d("goodi", "It's png & gif file");

        InputStream is = null;
        try {
            is = context.getAssets().open(uri.substring(1));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return newChunkedResponse(Response.Status.OK, MIME_PNG, is);

    } else if (uri.endsWith("json")) {
        Log.d("goodi", "It's json file");

        InputStream is = null;
        try {
            is = context.getAssets().open(uri.substring(1));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return newChunkedResponse(Response.Status.OK, MIME_PLAINTEXT, is);

    } else if (uri.endsWith("woff") || uri.endsWith("woff2")) {
        Log.d("goodi", "It's woff or woff2 file");

        InputStream is = null;
        try {
            is = context.getAssets().open(uri.substring(1));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return newChunkedResponse(Response.Status.OK, MIME_FONT, is);

    } else if (uri.endsWith("oga")) {
        Log.d("goodi", "It's oga file");

        InputStream is = null;
        try {
            is = context.getAssets().open(uri.substring(1));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return newChunkedResponse(Response.Status.OK, MIME_OGA, is);

    } else if (uri.endsWith("mp3")) {
        Log.d("goodi", "It's mp3 file");

        InputStream is = null;
        try {
            is = context.getAssets().open(uri.substring(1));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return newChunkedResponse(Response.Status.OK, MIME_MPEG, is);

    } else if (uri.endsWith("css")) {
        Log.d("goodi", "It's css file");

        InputStream is = null;
        try {
            is = context.getAssets().open(uri.substring(1));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return newChunkedResponse(Response.Status.OK, MIME_CSS, is);
    }

    Method method = session.getMethod();
    Log.d("goodi", "method = " + method);
    return newFixedLengthResponse(answer);
}
}

MainActivity.java

public class MainActivity extends AppCompatActivity {

    MyHTTPD server;

    @SuppressLint("SetJavaScriptEnabled")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        WebView webView = findViewById(R.id.web_view);
        webView.setWebViewClient(new MyWebViewClient());
        webView.setWebChromeClient(new WebChromeClient());
        webView.getSettings().setJavaScriptEnabled(true);
        webView.getSettings().setLoadsImagesAutomatically(true);
        webView.getSettings().setAppCacheEnabled(true);
        webView.getSettings().setUserAgentString("Mozilla/5.0 (Windows; U; Windows NT 6.1; en-GB; rv:1.9.1.2) Gecko/20090729 Firefox/3.5.2 (.NET CLR 3.5.30729)");

        server = new MyHTTPD(MyHTTPD.PORT, this);
        try {
            server.start();
        } catch (IOException e) {
            e.printStackTrace();
        }

        // указываем страницу загрузки
        webView.loadUrl("http://localhost:" + MyHTTPD.PORT);
    }

    private class MyWebViewClient extends WebViewClient {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            view.loadUrl(url);
            return true;
        }
    }

    @Override
    public void onPause() {
        server.stop();
        super.onPause();
    }
}

Разметка activity_main

<?xml version="1.0" encoding="utf-8"?>
<WebView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/web_view"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

Сайт лежит в assets. index.html там же.

Ваш ответ

Нажимая на кнопку «Отправить ответ», вы соглашаетесь с нашими условиями использования и подтверждаете, что прочитали и поняли наши политику конфиденциальности и нормы поведения.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.