拿到cookie之后,传递给httpclient完成业务逻辑的访问,现在把基本的流程整理记录一下。
首先来一张android工程的目录结构图吧,html、js文件都是放在assets下面的。
1、基本的html页面,index.html
Login
注意版本之间的差别,之前因为版本的不对,纠结了下。
2、JS登录的代码,login.js
$('#page_login_submit').live('click', function(){
var name = $('#page_login_name').val();
if (!name)
{
alert('Please enter your user name.');
return false;
}
var pass = $('#page_login_pass').val();
if (!pass)
{
alert('Please enter your password.');
return false;
}
// BEGIN
$.ajax({
url: "http://172.23.10.100/?q=rest_services/user/login.json",
type: 'post',
data: 'username=' + encodeURIComponent(name) + '&password=' + encodeURIComponent(pass),
dataType: 'json',
error: function(XMLHttpRequest, textStatus, errorThrown) {
console.log(JSON.stringify(XMLHttpRequest));
console.log(JSON.stringify(textStatus));
console.log(JSON.stringify(errorThrown));
alert('page_login_submit - failed to login');
},
success: function(data) {
alert(JSON.stringify(data));//注意,成功之后收到的data
}
});
// END
return false;
});
这里偷懒把成功返回的json文件直接通过alert,回传给webview了
具体的项目中,可以写个函数来接收
3、页面准备好了,下面我们开始webview的测试代码
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mWebView = (WebView)findViewById(R.id.webview);
WebSettings wSet = mWebView.getSettings();
wSet.setJavaScriptEnabled(true);
wSet.setJavaScriptCanOpenWindowsAutomatically(true);
//解决跨域访问的问题
try {
if (Build.VERSION.SDK_INT >= 16) {
Class> clazz = mWebView.getSettings().getClass();
Method method = clazz.getMethod(
"setAllowUniversalAccessFromFileURLs", boolean.class);
if (method != null) {
method.invoke(mWebView.getSettings(), true);
}
}
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
mWebView.clearCache(true);
CookieManager.getInstance().removeSessionCookie();
mWebView.loadUrl(URL);
mWebView.setWebChromeClient(new WebChromeClient(){
public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
//偷懒直接接收JS中传过来的msg
if(message.length() > 15){
mLoginBackJson = message;
Log.i(TAG, "mLoginBackJson = " + mLoginBackJson);
if(parseJson(mLoginBackJson)){//解析传回的json文件,成功的话,进行一次业务的访问
new MyTask().execute(ConfigUrl.ALL_CONTENT_VIEW);
}
//return true;
}
//保存一下cookie,后面httpclient使用
CookieManager cookieManager = CookieManager.getInstance();
CookieStr = cookieManager.getCookie(COOKIE_URL);
return super.onJsAlert(view, url, message, result);
}
});
}
activity_main.xml文件就比较简单了,只有一个webview。
String jsonResponse = UtilHttp.executeGet(url + "&sessid=" + mSessionId + "&session_name=" + mSessionName,
null, CookieStr);
public static DefaultHttpClient getHttpClient(){
BasicHttpParams httpParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParams, REQUEST_TIMEOUT);
HttpConnectionParams.setSoTimeout(httpParams, SO_TIMEOUT);
DefaultHttpClient client = new DefaultHttpClient(httpParams);
return client;
}
public static String executeGet(String url, List dataList, String cookie) {
try {
StringBuffer sbResult = new StringBuffer();
DefaultHttpClient client = getHttpClient();
if(dataList != null && dataList.size() > 0)
{
url+="?";
for(BasicHeader h:dataList){
url+=h.getName()+"="+h.getValue()+"&";
}
}
HttpGet httpGet = new HttpGet(url);
httpGet.setHeader("Cookie", cookie);//设置cookie
HttpResponse response = client.execute(httpGet);
sbResult = getResponse(sbResult, response);
Log.d(TAG,"executeGet url = "+url + " StatusCode:"+response.getStatusLine().getStatusCode());
if( response.getStatusLine().getStatusCode() != HttpStatus.SC_OK )
return null;
return sbResult.toString();
}catch (TimeoutException e) {
Log.d(TAG,"executeGet TimeoutException..");
return "timeout";
}catch (SocketTimeoutException e) {
Log.d(TAG,"executeGet SocketTimeoutException..");
return "timeout";
}catch (ConnectTimeoutException e) {
Log.d(TAG,"executeGet ConnectTimeoutException..");
return "timeout";
}catch(Exception e){
e.printStackTrace();
}
return null;
}