您的位置:首页 > 理论基础 > 计算机网络

android使用webview登录,获取session传递到httpclient小例子

2014-01-07 10:44 302 查看
前几天完成了一个客户端小功能,使用html页面登录,

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

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



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

<meta http-equiv="Access-Control-Allow-Origin" content="*">
<div data-role="page" id="page_login">

<meta http-equiv="Access-Control-Allow-Origin" content="*">
<link rel="stylesheet" href="jquery.mobile-1.0.min.css" />
<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>

<div data-role="header">
<h1>Login</h1>
</div><!-- /header -->

<div data-role="content" class='content'>
<div>
<label for="page_login_name">Username</label>
<input type="text" id="page_login_name" />
</div>
<div>
<label for="page_login_pass">Password</label>
<input type="password" id="page_login_pass" />
</div>
<fieldset>
<div><button type="button" data-theme="b" id="page_login_submit">Login</button></div>
</fieldset>
</div><!-- /content -->

</div><!-- /page -->


代码中需要的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。

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
>

<WebView
android:id ="@+id/webview"
android:layout_width ="match_parent"
android:layout_height ="match_parent"
/>
</RelativeLayout>


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<BasicHeader> 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,就证明成功了。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: