How to post data for WebView android

点点圈 提交于 2019-11-29 02:27:24

问题


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?


回答1:


Try like below...

 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());



回答2:


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.




回答3:


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

String postData = "fileContents=" + URLEncoder.encode(fileCon, "UTF-8");


来源:https://stackoverflow.com/questions/39506246/how-to-post-data-for-webview-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!