How to post data for WebView android - android

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

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.

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.

try this:
You need to URL-encode the parameter value before sending it.
String postData = "fileContents=" + URLEncoder.encode(fileCon, "UTF-8");

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. :-)

Related

How to programmatically open several pages in webview subsequently

I want to open a website in Kotlin and login programmatically to it. Then I want to open different pages of that website programmatically and read their information using JavaScript and save them in some variables in Kotlin.
So far, I have used web-view and I can login to website programmatically using following code:
var webview = WebView(this)
webview.settings.javaScriptEnabled = true
webview.settings.domStorageEnabled = true
webview.webViewClient = object: WebViewClient() {
override fun onPageFinished(view: WebView, url: String) {
webview.loadUrl("javascript: {" +
"document.getElementById('TXT_UserName').value = '" + password + "';" +
"document.getElementById('TXT_Password').value = '" + password + "';" +
"var frms = document.getElementById('btn_Login').click(); };")
}
})
}
}
webview.loadUrl("http://10.104.24.64/")
I know by using onPageFinished function,I can understand when the first page is loaded completely. But I don't know when other pages are loaded completely. This is important to me because before completely loading, I can't read their information and JavaScript returns null. Also I don't know exactly how to open a link to other page from the first page programmatically. Following code is executed in JavaScript successfully, but in Kotlin returns null.
val script = "var t= document. getElementById ('ContentPlaceHold');"
+"t.name"
webview. evaluateJavascript(script, object : ValueCallback<String> {
override fun onReceiveValue(value: String) {
//to save JavaScript variables in to Kotlin variables here
}
})
I think it's reason is that in Kotlin codes are executed asynchronously.
Can anyone help me?
Thanks in advance.

WebView is not using Cookies for loading images

I have troubles when I want my WebView to load images that requires Cookies.
I have set my cookies on the 'CookieManager'
final android.webkit.CookieManager instance = android.webkit.CookieManager.getInstance();
instance.setAcceptCookie(true);
instance.setCookie(".example.fr", mCookies, new ValueCallback<Boolean>() {
#Override
public void onReceiveValue(final Boolean value) {
loadWebView();
}
});
The WebView is then loaded with a custom HTML string because the app is generating the proper HTML.
private void loadWebView() {
// this string is an example of a generated HTML
String htmlContent =
"<!DOCTYPE html>" +
"<html><head>" +
"<link rel=\"stylesheet\" href=\"css/style.css\" type=\"text/css\" media=\"screen, projection\"/></head>" +
"<body><img src=\"www.example.fr/img.jpg\"/></body></html>";
mWebView.loadDataWithBaseUrl("file:///android_asset/", htmlContent, "text/html", "UTF-8", null);
}
I tried to proxy the network calls with Charles Proxy and I noticed that the request to www.example.fr/img.jpg had no cookie set in the headers. But, when I inspect the WebView using Chrome debbuging, I can see that the Cookies are properly under the Resources tab.
It seems that they are not used for the image downloading.
Any hints or advices to make the WebView using Cookies for resource downloading ?
Thank you.
I've faced with same problem, it is related with following changes:
https://developer.android.com/about/versions/android-5.0-changes.html#BehaviorWebView
to fix it you need set:
CookieManager.getInstance().setAcceptThirdPartyCookies(mWebView,true);

Webview not working if I am passing parameters to url in assets folder.?

I am working on an app where i need to pass parameters to url while loading html file in webview from assets folder. If I am passing parameters webview was not loading & If not it's working good. The following code is working in 2.1 & 2.3 versions but coming to 4.0 version it's not working.
code:
webview.loadUrl("file:///android_asset/index.html"); //this is working
webview.loadUrl("file:///android_asset/index.html?" + parameters); //this is not working
//to pass parameters I am adding "?" at the end & it's not working.
Can anyone please help me with any alternative code for passing parameters to the following url.
Could you add a JavaScript method to your HTML and pass the parameters in via that function after loading the page? Something like ...
<script type="text/javascript">
function receiveParameters(p) {
// Do something with p
}
</script>
webview.loadUrl("file:///android_asset/index.html");
webview.evaluateJavascript("receiveParameters(" + parameters + ");", null);
I have solved it...
String filePath = "/data/user/0/~/files/public";
//launchUrl = String.format("%s/index.html?id=test", filePath);
//-->
launchUrl = String.format("file://%s/index.html?id=test", filePath);
webview.loadUrl(launchUrl);
You can use shouldInterceptRequest to remove the query before assetLoader seek for the file:
webview.webViewClient = object : WebViewClient() {
override fun shouldInterceptRequest(
view: WebView,
request: WebResourceRequest
): WebResourceResponse? {
if (request.url.host == "appassets.androidplatform.net") {
// Do any logic you want to remove disturb parmeters
var url = request.url
if (request.url.queryParameterNames.contains("yourparam")) {
url = Uri.parse(request.url.toString().split("?")[0])
}
return assetLoader.shouldInterceptRequest(url)
}
}
}
Now your html will be available to handle the parameters. But the assets loader do not care.

pass two parameters with URL link in android

i have problem with two parameters passing with URL link. Can anyone help me?
private void FillDetails(String _userid,int _sporttype) {
al_TeamName=new ArrayList<String>();
try{
spf=SAXParserFactory.newInstance();
sp=spf.newSAXParser();
xr=sp.getXMLReader();
URL sourceUrl = new URL(
"http://10.0.2.2:2291/acd.asmx/Get_Teams?_userid ="+_userid & "_sporttype="+ _sporttype);
MyHandler mh=new MyHandler();
xr.setContentHandler(mh);
xr.parse(new InputSource(sourceUrl.openStream()));
setListAdapter(new MyAdapter());
}
catch(Exception ex)
{
}
}
when i using this code, i am getting null.If i send single parameter then it works fine.
Is this correct procedure for URL passing two parameters?
Thanks in advance..........
UPDATED ANSWER:
Now you have multiple errors in your URL:
URL sourceUrl = new URL("http://10.0.2.2:2291/acd.asmx/Get_Teams?_userid =" +
_userid & "_sporttype="+ _sporttype);
You still have a space before the first = sign
There's no + between the _userid variable and the rest of the string.
The & sign is outside the second string
It should be something like this:
URL sourceUrl = new URL("http://10.0.2.2:2291/acd.asmx/Get_Teams?_userid="
+ _userid + "&_sporttype=" + _sporttype);
ORIGINAL ANSWER:
You currently have a space instead of a = sign after your first parameter:
?_userid "+_userid
should be
?_userid="+_userid
Solved.
URL sourceUrl = new URL("http://0.0.0.0/acd.asmx/GetList?Value1="+Value1+"&ID="+ID);
"http://10.0.2.2:2291/acd.asmx/Get_Teams?_userid ="+_userid & "_sporttype="+ _sporttype);
You have an & after _userid, which probably does who knows what on _userid. Usually a single & does binary manipulation, so you might be transforming what comes out of _userid. Also, I would recommend URLEncoding your REST tags if you aren't doing that already
I would recommend logging the REST parameters while in development as well to double-check that it's being formed correctly
Update: The & was outside the quote and you needed to use a +
"http://10.0.2.2:2291/acd.asmx/Get_Teams?_userid ="+_userid + "&_sporttype="+ _sporttype);
If you came here because you searched for a version working in Kotlin (like me), you can use this function to build your URL:
import java.net.URL
// Your URL you want to append the query on
val url: String = "http://10.0.2.2:2291/acd.asmx/Get_Teams"
// The parameters you want to pass
val params: Map<String, String> = mapOf(
"_userid" to _user_id
, "_sporttype" to _sporttype
)
// The final build url. Standard encoding for URL is already utf-8
val final_url: URL = URL(
"$url?" // Don't forget the question-mark!
+ params.map {
"${it.key}=${it.value}"
}.joinToString("&")
)

Display a part of the webpage on the webview android

I want to make an app which loads the content from the webpage into webview. I want to show only a particular thing in the entire webview, not the whole content of the webpage.
Here is an example. If I use: http://us.m.yahoo.com/w/search%3B_ylt=A2KL8xs0vUBQMg0AwAkp89w4?submit=oneSearch&.intl=us&.lang=en&.tsrc=yahoo&.sep=fp&p=digital+cameras&x=0&y=0 as the URL for the webview, it loads all the contents of the page on the webview. But I want to remove the banner of the page and show it on the webview of my application.
I have tried using adblocker using CSS tags, but that is not helping me. Please give me some idea for overcoming this problem.
Thanks.
Thank You for the answer Zyber. I have solved it using injection of JavaScript in the code for WebView in android.
final WebView webview = (WebView)findViewById(R.id.browser);
webview.getSettings().setJavaScriptEnabled(true);
webview.setWebViewClient(new WebViewClient() {
#Override
public void onPageFinished(WebView view, String url)
{
webview.loadUrl("javascript:(function() { " +
"document.getElementsByTagName('header')[0].style.display="none"; " +
"})()");
}
});
webview.loadUrl("http://code.google.com/android");
This solved my purpose and it is easy to use to.
I got the solution to add this:
view.getSettings().setJavaScriptEnabled(true);
view.setWebViewClient(new WebViewClient() {
#Override
public void onPageFinished(WebView view, String url)
{
view.loadUrl("javascript:(function() { " +
"var head = document.getElementsByClassName('header')[0].style.display='none'; " +
"var head = document.getElementsByClassName('blog-sidebar')[0].style.display='none'; " +
"var head = document.getElementsByClassName('footer-container')[0].style.display='none'; " +
"})()");
}
});
view.loadUrl("your url");
Adding (var head =) looks like to hide my class in webview.
I hope this will be helpful for someone.
check Jsoup it provides an library which gives an easy way of extracting Html elements from a webpage
DefaultHttpClient client = new DefaultHttpClient();
HttpGet get = new HttpGet(url.toURI());
HttpResponse resp = client.execute(get);
String content = EntityUtils.toString(resp.getEntity());
Document doc = Jsoup.parse(content);
Elements ele = doc.select("div.classname");
This example executes an Http GET and then extracts an Div element with the class "classname" which you can then load in your webview

Categories

Resources