Hybrid – WebView session – 2

Hybrid–webview session maintenance

I want to write this blog for a long time, the main reason is When I first came into contact with session maintenance, all kinds of novices, most of the code crawled on the Internet was a bunch of nonsense or directly cheating people, all kinds of uncomfortable, yesterday just solved a session retention problem, I want to come to this time to also organize Almost, write here for yourself and those who need it—Panda Zhuo 20151119

Science

We need to know:
–1 .What is a session and what is a cookie?
In my opinion, if I understand, the session is saved on the server side, and the cookie is saved on the client side to mark the login status. There is a value in the cookie JSESSIONID=FHNHBXJJJXNAKDKCK (this value I just write) is consistent with the sessionId in the session. The server will think that you have already logged in. No need to log in again. The server will find the corresponding session based on this sessionId. Of course In web development, some parameters will be stored in the session, such as login user information, and the server will find the login user when it finds the session. On the contrary, if the session cannot be found or there are no related parameters in the session, it is considered that the user is not logged in or the session has expired due to a timeout, and the user is prompted to log in again.
-2. Why session retention is needed in webview?
This problem is obvious. If you do not do session retention, most of the web page access on the web side is filtered through the session, and you cannot access any page without a session. Of course, some students said that some jsp and actions can be configured not to be filtered, but do you think this is really good? ?

Code Talking

-1. Obtaining sessionId
Or it should be said that obtaining the cookie, we need to obtain the JSESSIONID in the cookie and save it on the client The next time you visit the page, you should bring a cookie to tell the server that you have logged in and you can safely let it go.
The author’s realization idea in his project is this: write a servlert or action in the web project to realize login. Android accesses the login method through urlConnection, and the sessionId after successful login is returned to the client to save. br />// Open the link according to the URL object
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
// Set the request method
urlConnection.setRequestMethod(“POST”);< br />// Set the timeout of the request
urlConnection.setReadTimeout(8000); urlConnection.setConnectTimeout(8000);
// Data passed
String data = “userName=” + URLEncoder .encode(username, “UTF-8”)
+ “&pwd=” + URLEncoder.encode(pwd, “UTF-8”)+ “&device=” + URLEncoder.encode(“mobile”, “UTF- 8”);
// Set the request header
urlConnection.setRequestProperty(“Connection”, “keep-alive”);
// Set the request header
urlConnection.setRequestProperty (“Content-Type”, “application/x-www-form-urlencoded”);
// Set the request header
urlConnection.setRequestProperty(“Content-Length”, String.valueOf(data. getBytes().length));
// Set the request header
urlConnection.setRequestProperty(“User-Agent”,”Mozilla/5.0 (Window s NT 6.3; WOW64; rv:27.0) Gecko/20100101 Firefox/27.0″);
urlConnection.setUseCaches(false);
urlConnection.setDoOutput(true);
// Send POST request Must be set to allow input
urlConnection.setDoInput(true); // To send a POST request must be set to allow input
//The default value of setDoInput is true
//Get output stream
OutputStream os = urlConnection.getOutputStream();
os.write(data.getBytes());
os.flush();
String yyu = urlConnection.getResponseMessage();
if (urlConnection.getResponseCode() == 200) {
// Get the input stream object of the response
InputStream is = urlConnection.getInputStream();
// Create a byte output stream object< br />ByteArrayOutputStream baos = new ByteArrayOutputStream();
// Define the read length
int len ​​= 0;
// Define the buffer
byte buffer[] = new byte[1024];
// According to the size of the buffer, read circularly
while ((len = is.read(buffer)) != -1) {
// According to the read Write the taken length into the os object
baos.write(buffer, 0, len);
}
// Release resources
is.close();
baos.close();
// return string
final String result = new String(baos.toByteArray());

We have successfully obtained se above ssionId, as for local saving, readers can choose file, sharedpreference, db to save.

How does webview carry session access page

Use Android’s CookieSyncManage to synchronize cookies to URL
For specific usage, readers are recommended to go directly Check the official api
CookieSyncManager
A brief summary of online practices generally use asynchronous tasks ansyTask to complete the time-consuming operation of webview access, here to save the need for self-duty.
Code Speaking

public static void syncCookie(Context context, String url, String jessionid) {
try {
Log.v(TAG,"sfq-syncCookie:"+ jessionid);
CookieSyncManager.createInstance(context);
CookieSyncManager.getInstance().startSync();
CookieManager cookieManager = CookieManager.getInstance();
cookieManager.setAcceptCookie(true );
//Some tests have found that the operation of clearing cookies will cause accidental failure of cookies.
cookieManager.removeSessionCookie();// Remove
cookieManager.removeAllCookie();
String oldCookie = cookieManager.getCookie(url);
/* StringBuilder sbCookie = new StringBuilder();
sbCookie.append(String.format("JSESSIONID=%s", jessionid));< br /> String cookieValue = sbCookie.toString();*/


cookieManager.setCookie(url, jessionid);

String newCookie = cookieManager.getCookie( url);
if (newCookie != null) {
//Talk about ne here wCookie save locally
}
CookieSyncManager.getInstance().sync();
} catch (Exception e) {
Log.e(TAG, e.toString());
}
}

Above, the author will keep the method independent as a tool class, which is very convenient to use.

Ultimate webview gorgeous integration

The code used for webview comes from a web blog

The quoted blog address

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.os.Message;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit .WebViewClient;

public class WebViewBase extends WebView {
private static final String DEFAULT_URL = "http://www.ijinshan.com/";
private Activity mActivity;
public WebViewBase(Context context) {
super(context);
mActivity = (Activity) context;
init(context);
}

@SuppressLint("SetJavaScriptEnabled")
private void init(Context context) {
WebSettings webSettings = this.getSettings();
webSettings.setJavaScriptEnabled(true);
webSettings.setSupportZoom(true);
//webSettings.setUseWideViewPort(true);
this.setWebViewClient(mWebViewClientBase);
this.setWebChromeClient(mWebChromeClientBase);
//Author of this article Panda Zhuo reminded me to add the session retention code here, and you're done.
syncCookie(Context context, String url, String jessionid)
this.loadUrl(DEFAULT_URL);
this.onResume();
}

private WebViewClientBase mWebViewClientBase = new WebViewClientBase();

private class WebViewClientBase extends WebViewClient {

@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
// TODO Auto-generated method stub
return super.shouldOverrideUrlLoading(view, url);
}

@Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
// TODO Auto-generated method stub
super.onPageStarted(view, url, favicon);
}

@Override
public void onPageFinished(WebView view, String url) {
// TODO Auto-generated method stub
super.onPageFinished(view, url);
}

@Override
public void onReceivedError(WebView view, in t errorCode,
String description, String failingUrl) {
// TODO Auto-generated method stub
super.onReceivedError(view, errorCode, description, failingUrl);
}

@Override
public void doUpdateVisitedHistory(WebView view, String url,
boolean isReload) {
// TODO Auto-generated method stub
super.doUpdateVisitedHistory( view, url, isReload);
}
}

private WebChromeClientBase mWebChromeClientBase = new WebChromeClientBase();

private class WebChromeClientBase extends WebChromeClient {

@Override
public void onProgressChanged(WebView view, int newProgress) {
mActivity.setProgress(newProgress * 1000);
}

@ Override
public void onReceivedTitle(WebView view, String title) {
// TODO Auto-generated method stub
super.onReceivedTitle(view, title);
}
< br /> @Override
public void onReceivedTouchIconUrl(WebView view, String url,
boolean precomposed) {
// TODO Auto-generated method stub
super.onReceivedTouchIconUrl(view, url , precomposed);
}

@Override
public boolean onCreateWindow(WebView view, boolean isDialog,
boolean isUserGesture, Message resultMsg) {
// TODO Auto-generated method stub
return super.onCreateWindow(view, isDialog, isUserGesture, resultMsg);
}

}
}

If you need or don’t give special instructions, during the test, I found that the session was always lost when the second-level jsp page directly under the homepage was directly lost. The session can be maintained by accessing the second-level jsp in the form of buttons on the level-level jsp interface. In the end, I didn’t understand why this is the difference between a parameter written on the url. Please understand this kind of people to answer questions! Thank you. Because of my actual problem, it is recommended that when using the syncCookie (Context context, String url, String jessionid) method, the parameter url fills in the first-level url, and the url in webview.loadUrl (targetUrl) fills in the url that you actually want to see. Don’t ask me why, you know please tell me.

Hybrid–webview session maintenance

I want to write this blog It’s been a long time, the main reason is that when I first started contacting session retention, all the novices, most of the code crawled on the Internet was a bunch of nonsense or directly cheating people, all kinds of uncomfortable, just solved a session retention problem yesterday. , I want to come to this time and I have sorted it out almost, write it here for myself and those who need it—Panda Zhuo20151119

Science

We Need to know:
-1. What is a session and what is a cookie?
From my point of view, if I understand, the session is stored on the server side, and the cookie is stored on the client side to mark the login status. There is a value in the cookie JSESSIONID=FHNHBXJJJXNAKDKCK (this value I just write) is consistent with the sessionId in the session. The server will think that you have already logged in. No need to log in again. The server will find the corresponding session based on this sessionId. Of course In web development, some parameters will be stored in the session, such as login user information, and the server will find the login user when it finds the session. On the contrary, if the session cannot be found or there are no related parameters in the session, it is considered that the user is not logged in or the session has expired due to a timeout, and the user is prompted to log in again.
-2. Why session retention is needed in webview?
This problem is obvious. If you do not do session retention, most of the web page access on the web side is filtered through the session, and you cannot access any page without a session. Of course, some students said that some jsp and actions can be configured not to be filtered, but do you think this is really good? ?

Code Talking

-1. Obtaining sessionId
Or it should be said that obtaining the cookie, we need to obtain the JSESSIONID in the cookie and save it on the client The next time you visit the page, you should bring a cookie to tell the server that you have logged in and you can safely let it go.
The author’s realization idea in his project is this: write a servlert or action in the web project to realize login. Android accesses the login method through urlConnection, and the sessionId after successful login is returned to the client to save. br />// Open the link according to the URL object
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
// Set the request method
urlConnection.setRequestMethod(“POST”);< br />// Set the timeout of the request
urlConnection.setReadTimeout(8000); urlConnection.setConnectTimeout(8000);
// Data passed
String data = “userName=” + URLEncoder .encode(username, “UTF-8”)
+ “&pwd=” + URLEncoder.encode(pwd, “UTF-8”)+ “&device=” + URLEncoder.encode(“mobile”, “UTF- 8”);
// Set the request header
urlConnection.setRequestProperty(“Connection”, “keep-alive”);
// Set the request header
urlConnection.setRequestProperty (“Content-Type”, “application/x-www-form-urlencoded”);
// Set the request header
urlConnection.setRequestProperty(“Content-Length”, String.valueOf(data. getBytes().length));
// Set the request header
urlConnection.setRequestProperty(“User-Agent”,”Mozilla/5.0 (Windows NT 6.3; WOW64; rv:27.0) Gecko/20100101 Firefox/27.0″);
urlConnection.setUseCaches(false);
urlConnection.setDoOutput(true);
// Required to send POST request Set the allowable input
urlConnection.setDoInput(true); // To send a POST request, you must set the allowable input
//The default value of setDoInput is true
//Get the output stream
OutputStream os = urlConnection.getOutputStream();
os.write(data.getBytes());
os.flush();
String yyu = urlConnection.getResponseMessage();
if (urlConnection.getResponseCode() == 200) {
// Get response input stream object
InputStream is = urlConnection.getInputStream();
// Create byte output stream object
ByteArrayOutputStream baos = new ByteArrayOutputStream();
// Define the read length
int len ​​= 0;
// Define the buffer
byte buffer[] = new byte [1024];
// According to the size of the buffer, read circularly
while ((len = is.read(buffer)) != -1) {
// According to read The length of is written into the os object
baos.write(buffer, 0, len);
}
// Release resources
is.close();
baos.close();
// return string
final String result = new String(baos.toByteArray());

We have successfully obtained sess above ionId, as for local saving, readers can choose file, sharedpreference, db to save.

How does webview carry session access page

Use Android’s CookieSyncManage to synchronize cookies to URL
For specific usage, readers are recommended to go directly Check the official api
CookieSyncManager
A brief summary of online practices generally use asynchronous tasks ansyTask to complete the time-consuming operation of webview access, here to save the need for self-duty.
Code Speaking

public static void syncCookie(Context context, String url, String jessionid) {
try {
Log.v(TAG,"sfq-syncCookie:"+ jessionid);
CookieSyncManager.createInstance(context);
CookieSyncManager.getInstance().startSync();
CookieManager cookieManager = CookieManager.getInstance();
cookieManager.setAcceptCookie(true );
//Some tests have found that the operation of clearing cookies will cause accidental failure of cookies.
cookieManager.removeSessionCookie();// Remove
cookieManager.removeAllCookie();
String oldCookie = cookieManager.getCookie(url);
/* StringBuilder sbCookie = new StringBuilder();
sbCookie.append(String.format("JSESSIONID=%s", jessionid));< br /> String cookieValue = sbCookie.toString();*/


cookieManager.setCookie(url, jessionid);

String newCookie = cookieManager.getCookie( url);
if (newCookie != null) {
//Talk about new here Cookie local storage
}
CookieSyncManager.getInstance().sync();
} catch (Exception e) {
Log.e(TAG, e.toString());
}
}

Above, the author will keep the method independent as a tool class, which is very convenient to use.

Ultimate webview gorgeous integration

The code used for webview comes from a web blog

The quoted blog address

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.os.Message;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit .WebViewClient;

public class WebViewBase extends WebView {
private static final String DEFAULT_URL = "http://www.ijinshan.com/";
private Activity mActivity;
public WebViewBase(Context context) {
super(context);
mActivity = (Activity) context;
init(context);
}

@SuppressLint("SetJavaScriptEnabled")
private void init(Context context) {
WebSettings webSettings = this.getSettings();
webSettings.setJavaScriptEnabled(true);
web Settings.setSupportZoom(true);
//webSettings.setUseWideViewPort(true);
this.setWebViewClient(mWebViewClientBase);
this.setWebChromeClient(mWebChromeClientBase);
//Author of this article Panda Zhuo reminded me to add the session retention code here, and you're done.
syncCookie(Context context, String url, String jessionid)
this.loadUrl(DEFAULT_URL);
this.onResume();
}

private WebViewClientBase mWebViewClientBase = new WebViewClientBase();

private class WebViewClientBase extends WebViewClient {

@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
// TODO Auto-generated method stub
return super.shouldOverrideUrlLoading(view, url);
}

@Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
// TODO Auto-generated method stub
super.onPageStarted(view, url, favicon);
}

@Override
public void onPageFinished(WebView view, String url) {
// TODO Auto-generated method stub
super.onPageFinished(view, url);
}

@Override
public void onReceivedError(WebView view, in t errorCode,
String description, String failingUrl) {
// TODO Auto-generated method stub
super.onReceivedError(view, errorCode, description, failingUrl);
}

@Override
public void doUpdateVisitedHistory(WebView view, String url,
boolean isReload) {
// TODO Auto-generated method stub
super.doUpdateVisitedHistory( view, url, isReload);
}
}

private WebChromeClientBase mWebChromeClientBase = new WebChromeClientBase();

private class WebChromeClientBase extends WebChromeClient {

@Override
public void onProgressChanged(WebView view, int newProgress) {
mActivity.setProgress(newProgress * 1000);
}

@ Override
public void onReceivedTitle(WebView view, String title) {
// TODO Auto-generated method stub
super.onReceivedTitle(view, title);
}
< br /> @Override
public void onReceivedTouchIconUrl(WebView view, String url,
boolean precomposed) {
// TODO Auto-generated method stub
super.onReceivedTouchIconUrl(view, url , precomposed);
}

@Override
public boolean onCreateWindow(WebView view, boolean isDialog,
boolean isUserGesture, Message resultMsg) {
// TODO Auto-generated method stub
return super.onCreateWindow(view, isDialog, isUserGesture, resultMsg);
}

}
}

If you need or don’t give special instructions, during the test, I found that the session was always lost when the second-level jsp page directly under the homepage was directly lost. The session can be maintained by accessing the second-level jsp in the form of buttons on the level-level jsp interface. In the end, I didn’t understand why this is the difference between a parameter written on the url. Please understand this kind of people to answer questions! Thank you. Because of my actual problem, it is recommended that when using the syncCookie (Context context, String url, String jessionid) method, the parameter url fills in the first-level url, and the url in webview.loadUrl (targetUrl) fills in the url that you actually want to see. Don’t ask me why, you know please tell me.

Leave a Comment

Your email address will not be published.