Search code examples
androidhttp-postandroid-webview

How to post data for WebView android


I need to post data to Webview.
I found from some of the links the below code:

 WebView webview = new WebView(this);
 setContentView(webview);
 String url = "http://www.example.com";
 String postData = username=my_username&password=my_password";
 webview.postUrl(url",EncodingUtils.getBytes(postData, "BASE64"));

But in my android studio I see EncodingUtils as deprecated
Can anyone help me what is the alternative for EncodingUtils to post data to Android WebView?


Solution

  • Try like below...

    Java:

     WebView webview = new WebView(this);
     setContentView(webview);
    
     String url = "http://www.example.com";
    
     String postData = "username=" + URLEncoder.encode(my_username, "UTF-8") + "&password=" + URLEncoder.encode(my_password, "UTF-8");
     webview.postUrl(url,postData.getBytes());
    

    Kotlin:

    val webview = WebView(this)
    setContentView(webview)
    
    val url = "http://www.example.com"
    
    val postData = "username=${URLEncoder.encode(my_username, "UTF-8")}" +
    "&password=${URLEncoder.encode(my_password, "UTF-8")}"
    webview.postUrl(url, postData.toByteArray())