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?
Try like below...
try this: You need to URL-encode the parameter value before sending it.
I would like to add a few things to the answer as I had to work on same and found some info could help complete the answer to this question.
Second thing is that the URL you are opening needs to perform some operations right. Hence you must enable your webView to enable such operations or else things might not work. For example if your URL is executing some java script, than you must enable java script for your webview. This can be done as shown below :
Normally this will enable trivial things such as timers, returning results etc on your webview.
Third thing is a case when your webView needs to call methods of your android app. This can be done by adding some JavaScript Interface as shown below :
Where WebAppInterface() is a simple class which atleast one method annotated with @JavascriptInterface as shown below :
The name Android will be the one which will be injected into your URL as a variable and you can call the methods of your android WebAppInterace from that URL as shown below:
Android.showToast("From WebPage")
Last thing is your postURL method which is somewhat like :
This method has couple of things that it takes as default. First is that request type is taken as default POST as the name suggest.
Header content-type can be default taken as
application/x-www-form-urlencoded
and most important params it takes as & separated key value pairs as shown :We must pass byteArray of this string which is shown in post URL callback.
Now after your API is hit and it in some cases loads a callback url, from that call back URL using the JavaScript Interface, you can return result to your application and close the webview.
I hope it helps people.
This is a simple workaround.
I know this is not the best method but this works.