33

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?

Jonik
  • 80,077
  • 70
  • 264
  • 372

5 Answers5

79

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())
Vishal Naikawadi
  • 419
  • 6
  • 11
Priyank Patel
  • 12,244
  • 8
  • 65
  • 85
  • 3
    for Kotlin use toByteArray instead of getBytes – Andy Weinstein Dec 12 '19 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 Nov 14 '22 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.

kmchmk
  • 592
  • 9
  • 16
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.

Tarun Deep Attri
  • 8,174
  • 8
  • 41
  • 56
1

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

String postData = "fileContents=" + URLEncoder.encode(fileCon, "UTF-8");
Rahul Khurana
  • 8,577
  • 7
  • 33
  • 60
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. :-)

Aury0n
  • 217
  • 3
  • 14