DEV Community

Akira Kashihara
Akira Kashihara

Posted on

6 3

How to Display a Web Application with Basic Authentication in WebView using Jetpack Compose (Android)

This article shows how to display a web application with Basic Authentication in WebView using Jetpack Compose.
The sample code on this article was made with reference to the thread on StackOverflow. StackOverflow's code is written in Java, but this article shows you the sample code in kotlin.

Source Code

class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent{ MyWebClient(url = "https://hogehoge.hoge")}
    }
}

@SuppressLint("SetJavaScriptEnabled")
@Composable
fun MyWebClient(url: String) {

    AndroidView(factory = ::WebView,
    update = { webView ->
        webView.webViewClient = MyWebViewClient()
        webView.settings.javaScriptEnabled = true
        webView.loadUrl(url)

    })
}

// Ovverride onReceivedHttpAuthRequest in new class which extends WebViewClient().
private class MyWebViewClient: WebViewClient() {
    @Override
    override fun onReceivedHttpAuthRequest(
        view: WebView?,
        handler: HttpAuthHandler?,
        host: String?,
        realm: String?
    ) {
        if (handler != null) {
            handler.proceed("The user name to Basic Auth.", "The password to Basic Auth.")
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

The Result

I cannot show you the contents of the web application. But I guess that you can check that all contents (text and images) are loaded.

The Preview of Execution


This original article is the following that is written by me. This is a translation of a portion of this original article from Japanese to English.

Image of Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read more

Top comments (0)

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up