展会信息港展会大全

android使用webview登录,获取session传递到httpclient小例子
来源:互联网   发布日期:2015-10-02 21:28:24   浏览:2920次  

导读:前几天完成了一个客户端小功能,使用html页面登录,拿到cookie之后,传递给httpclient完成业务逻辑的访问,现在把基本的流程整理记录一下。首先来一张android工程的目录结构...

前几天完成了一个客户端小功能,使用html页面登录,

拿到cookie之后,传递给httpclient完成业务逻辑的访问,现在把基本的流程整理记录一下。

首先来一张android工程的目录结构图吧,html、js文件都是放在assets下面的。

1、基本的html页面,index.html

<script src="jquery-1.6.4.min.js"></script>

<script src="jquery.mobile-1.0.min.js"></script>

<script type="text/javascript" charset="utf-8" src="scripts/login.js"></script>

Login

Username

Password

Login

代码中需要的jquery-1.6.4.min.js、jquery.mobile-1.0.min.js、jquery.mobile-1.0.min.css,请自己去官网上面下载吧

注意版本之间的差别,之前因为版本的不对,纠结了下。

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。

4、最后是一次http get请求,做一次业务的访问了。

String jsonResponse = UtilHttp.executeGet(url + "&sessid=" + mSessionId + "&session_name=" + mSessionName,

null, CookieStr);

主要参数CookieStr,httpclient里面会使用到。

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;

}

如果我们拿到的jsonResponse的值不是null,就证明成功了。

赞助本站

人工智能实验室

相关热词: android开发 教程

AiLab云推荐
推荐内容
展开

热门栏目HotCates

Copyright © 2010-2024 AiLab Team. 人工智能实验室 版权所有    关于我们 | 联系我们 | 广告服务 | 公司动态 | 免责声明 | 隐私条款 | 工作机会 | 展会港