35

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?

5 Answers 5

80

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())
2
  • 3
    for Kotlin use toByteArray instead of getBytes Commented Dec 12, 2019 at 10:59
  • nice. also, if your parameters are in a hashmap, you can simplify to this: val postData = params.toList().joinToString(separator = "&") { "${it.first}=${URLEncoder.encode(it.second, "UTF-8")}" }
    – Raphael C
    Commented Nov 14, 2022 at 15:02
7

This is a simple workaround.

String html = "<!DOCTYPE html>" +
    "<html>" +
    "<body onload='document.frm1.submit()'>" +
    "<form action='http://www.yoursite.com/postreceiver' method='post' name='frm1'>" +
    "  <input type='hidden' name='foo' value='12345'><br>" +
    "  <input type='hidden' name='bar' value='23456'><br>" +
    "</form>" +
    "</body>" +
    "</html>";
webview.loadData(html, "text/html", "UTF-8");

I know this is not the best method but this works.

5

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.

  • First thing is the need for such a scenario. My need was that I am creating a payment gateway client for native applications in android.
  • 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 :

       val set = webview.settings
       set.javaScriptEnabled = true 
    

    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 :

        webview.addJavascriptInterface(WebAppInterface(), "Android")
    

    Where WebAppInterface() is a simple class which atleast one method annotated with @JavascriptInterface as shown below :

    class WebAppInterface() {
    
        @JavascriptInterface
        fun showToast(status: String) {
            //show toast here or handle status
        }
    }
    

    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 :

        webview.postUrl(actionUrl, params.toByteArray(Charsets.UTF_8))
    

    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 :

        val params = "MERCHANT_ADDR=" + addr + "&CHANNEL=android"

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.

0
1

try this: You need to URL-encode the parameter value before sending it.

String postData = "fileContents=" + URLEncoder.encode(fileCon, "UTF-8");
3
  • how to pass username , password ?? Commented Sep 15, 2016 at 9:02
  • you can do something like "postvar=value&foo=bar". Let me know if this works for you. Commented Sep 15, 2016 at 9:10
  • u mean to say : String postdata = username=+URLEncoder.encode(my_username,"UTF-8") & password=+URLEncoder.encode(my_password,"UTF-8"); webview.postUrl(url",postdata ); Commented Sep 15, 2016 at 9:17
0

For those who came here by trying to put a html body as a postData and not working, try to put your string body as something below:

    val htmlCode = "https://ramdom.user.me"

    val postData = "{\n" +
            "\t\"token\": \"963966f649\"\n" + "}"

    webview.postUrl(htmlCode, postData.toByteArray())

I hope to save someone`s life. :-)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.