How to post data for WebView android

Issue

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  usernamemy_username&passwordmy_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())

Answered By – Priyank Patel

Leave a Comment