Maintain sessions between the loadUrl and PostUrl of the Android WebView
I log in to my site using the PostUrl of the android WebView and it
works fine and shows the home page of my site, but with the method of using the LoadUrl
of the WebView
it asks me to log in again, the user is redirected to the login page. I searched a lot and found a lot of answers, but none of them worked for me. Here is my code :
WebView wb;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_antivirus, container, false);
CookieSyncManager.createInstance(getActivity().getBaseContext());
CookieSyncManager.getInstance().startSync();
CookieManager cookieManager = CookieManager.getInstance();
cookieManager.setAcceptCookie(true);
wb = (WebView)rootView.findViewById(R.id.Pardakht);
wb.getSettings().setJavaScriptEnabled(true);
wb.setWebViewClient(new WebViewClient() {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
return false;
}
@Override
public void onPageFinished(WebView view, String url) {
CookieSyncManager.getInstance().sync();
}
});
log in to my website successfully <~~~
String url="http://crm.example.com/user.php?op=bG9naW4=";
String postData="hidlogin=1&username="+username+"&password="+password+"&submit=%D9%88%D9%86%D9%87";
wb.postUrl(url, EncodingUtils.getBytes(postData, "BASE64"));
CookieSyncManager.getInstance().sync();
when i want to open new page it will be redirected to login page
wb.loadUrl("http://crm.example.com/customer.php?action=trafik");
return rootView;
}
Solution
You cannot call wb.postUrl() and then call it almost immediately after calling wb.loadUrl().
Before calling the second operation, you must let the first operation complete.
When you execute the second loadUrl(), the first postUrl() is not finished yet, so when loadUrl() is called, WebView
does not have a session cookie, which is followed by
postUrl()
The response is returned. The CookieManager
code may not be required; You can take it all out.
If you need to call them one after the other, use onPageFinished()
to determine when the post is done so you can start the next :
@Override
public void onPageFinished(WebView view, String url) {
if (url.startsWith("http://crm.example.com/user.php") {
wb.loadUrl("http://crm.example.com/customer.php?action=trafik");
}
}
Take out all the CookieManager
/CookieSyncManager
stuff and try this.
Can you put PHP code on this server? You should consider using a URL to get username/password data and display your customer.php action=trafik
page.