前幾天完成瞭一個客戶端小功能,使用html頁面登錄,
拿到cookie之後,傳遞給httpclient完成業務邏輯的訪問,現在把基本的流程整理記錄一下。
首先來一張android工程的目錄結構圖吧,html、js文件都是放在assets下面的。
1、基本的html頁面,index.htmlvcD4KPHA+PC9wPgo8cHJlIGNsYXNzPQ==”brush:java;”>
<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
代碼中需要的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: "https://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,就證明成功瞭。