編輯:關於Android編程
拿到cookie之後,傳遞給httpclient完成業務邏輯的訪問,現在把基本的流程整理記錄一下。
首先來一張android工程的目錄結構圖吧,html、js文件都是放在assets下面的。

1、基本的html頁面,index.html<喎?/kf/ware/vc/" target="_blank" class="keylink">vcD4KPHA+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>
注意版本之間的差別,之前因為版本的不對,糾結了下。
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, ListdataList, 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; }
關於Android的Button響應頁面跳轉問題
一般來說,Android應用程序中的Button響應事件有兩種書寫方式 Button button=null; button.setOnClickListener(n
Android客戶端性能優化(魅族資深工程師毫無保留奉獻)
本文由魅族科技有限公司資深Android開發工程師degao(嵌入式企鵝圈原創團隊成員)撰寫,是degao在嵌入式企鵝圈發表的第一篇原創文章,毫無保留地總結分享其在領導魅
UI控件之顯示圖像控件ImageView(上)
(一)概述ImageView主要是用來顯示圖片的控件,可以對圖片進行放大、縮小和旋轉的功能。(二)ImageView中src和BackGround屬性的區別No.1 &m
Android Demo手機獲取驗證碼
注冊很多app或者網絡賬戶的時候,經常需要手機獲取驗證碼,來完成注冊,那時年少,只是覺得手機獲取驗證碼這件事兒很好玩,並沒有關心太多,她是如何實現的,以及她背後的故事到底