編輯:關於 Android 程式設計
週末參觀了一場 36 小時編程比賽,現場氣氛相當熱烈。其中一個團隊想做出一個需要接入公司內域帳號登入的行動應用,最後卻卡在登入環節。由於我平常就在做 CAS,這塊相對熟悉,加上使用域帳號登入內部系統的場景越來越多,於是決定動手寫一個 demo。
說做就做,週六晚上回到住處便開始了我的「36 小時」開發。
先理清整體思路:CAS 的流程其實不算複雜,只要把瀏覽器中的整套流程在 Android 上重現即可。核心的 GlodonCas 類別如下:
package com.glodon.cas.model;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
public class GlodonCas {
private static DefaultHttpClient httpClient = new DefaultHttpClient();
private static boolean casLogined = false;
public final static String CAS_DOMAIN = "https://cas.grandsoft.com.cn";
public String appCallback = null;
private boolean isLogined = false;
public GlodonCas(String appCallback) {
this.appCallback = appCallback;
}
public boolean login(String username, String password) throws Exception {
String service = appCallback;
String lt = getLt();
String loginApi = CAS_DOMAIN + "/login";
String params = "username=" + URLEncoder.encode(username)
+ "&password=" + URLEncoder.encode(password)
+ "<=" + URLEncoder.encode(lt)
+ "&service=" + service;
byte[] entitydata = params.getBytes();
HttpURLConnection c = (HttpURLConnection) new URL(loginApi).openConnection();
c.setInstanceFollowRedirects(false);
c.setRequestMethod("POST");
c.setDoOutput(true);
c.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
c.setRequestProperty("Content-Length", String.valueOf(entitydata.length));
OutputStream outStream = c.getOutputStream();
outStream.write(entitydata);
outStream.flush();
outStream.close();
int responeCode = -1;
try {
responeCode = c.getResponseCode();
} catch (java.io.IOException e) {
if (e.getMessage().contains("authentication challenge")) {
responeCode = 401;
} else {
throw e;
}
}
if (responeCode == 303) {
get(c.getHeaderField("Location"));
isLogined = true;
casLogined = true;
return true;
} else {
isLogined = false;
casLogined = true;
return false;
}
}
public boolean isLogined() { return isLogined; }
public static boolean casLogined() { return casLogined; }
public static DefaultHttpClient getHttpClient() { return httpClient; }
private static String getLt() throws IOException {
String httpUrl = CAS_DOMAIN + "/loginTicket";
HttpPost httpPost = new HttpPost(httpUrl);
HttpResponse httpRespone = httpClient.execute(httpPost);
HttpEntity httpEntity = httpRespone.getEntity();
InputStream inputStream = httpEntity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
String str = "";
String line = null;
while ((line = reader.readLine()) != null) {
str += line;
}
return str;
}
private static String get(String httpUrl) throws Exception {
HttpGet httpGet = new HttpGet(httpUrl);
InputStream inputStream = null;
String bodyStr = "";
HttpResponse httpRespone = httpClient.execute(httpGet);
HttpEntity httpEntity = httpRespone.getEntity();
inputStream = httpEntity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
String line = "";
while ((line = reader.readLine()) != null) {
bodyStr += line;
}
return bodyStr;
}
}
再加上 Activity 的控制程式碼,整體終於跑通。接著還缺一個重點:在應用內用瀏覽器元件顯示登入後的網頁。思路很簡單——從 httpClient 取得登入後的 cookie,再植入 WebView 即可。稍加搜尋找到相關寫法,改一改、加上重新整理按鈕,就搞定了。
package com.glodon.cas.activities;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.cookie.Cookie;
import android.app.Activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.glodon.cas.model.GlodonCas;
public class MainActivity extends Activity {
private Button btnGetThinkList;
private static int LOGIN_REQUEST_CODE = 1;
private TextView tvThinkList;
private WebView webView;
private Button btnRefresh;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnGetThinkList = (Button) findViewById(R.id.btnGetThinkList);
tvThinkList = (TextView) findViewById(R.id.tvThinkList);
webView = (WebView) findViewById(R.id.webView);
btnGetThinkList.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (!GlodonCas.casLogined()) {
startActivityForResult(new Intent(MainActivity.this, LoginActivity.class), LOGIN_REQUEST_CODE);
return;
}
new ThinkListTask().execute();
}
});
webView.getSettings().setJavaScriptEnabled(true);
webView.setWebViewClient(new WebViewClient() {
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return false;
}
});
webView.loadUrl("https://think.grandsoft.com.cn");
btnRefresh = (Button) findViewById(R.id.btnRefresh);
btnRefresh.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
List cookies = GlodonCas.getHttpClient().getCookieStore().getCookies();
if (!cookies.isEmpty()) {
Cookie sessionCookie = null;
for (int i = 0; i < cookies.size(); i++) {
sessionCookie = cookies.get(i);
}
CookieSyncManager.createInstance(MainActivity.this);
CookieManager cookieManager = CookieManager.getInstance();
if (sessionCookie != null) {
cookieManager.removeSessionCookie();
String cookieString = sessionCookie.getName() + "=" + sessionCookie.getValue()
+ "; domain=" + sessionCookie.getDomain();
cookieManager.setCookie("think.grandsoft.com.cn", cookieString);
CookieSyncManager.getInstance().sync();
}
webView.loadUrl("https://think.grandsoft.com.cn");
}
}
});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == LOGIN_REQUEST_CODE) {
Toast.makeText(this, R.string.login_success, Toast.LENGTH_LONG).show();
}
}
class ThinkListTask extends AsyncTask {
@Override
protected String doInBackground(Void... params) {
try {
HttpGet httpGet = new HttpGet("https://think.grandsoft.com.cn/api/weekly_journals");
HttpClient httpClient = GlodonCas.getHttpClient();
HttpResponse httpRespone = httpClient.execute(httpGet);
StringBuilder sb = new StringBuilder();
HttpEntity httpEntity = httpRespone.getEntity();
InputStream inputStream = httpEntity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
String line = "";
while ((line = reader.readLine()) != null) {
sb.append(line);
}
return sb.toString();
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
@Override
protected void onPostExecute(String thinkList) {
tvThinkList.setText(thinkList);
}
}
}
登入頁 LoginActivity 則負責收集帳密、呼叫 GlodonCas 登入並回傳結果:
package com.glodon.cas.activities;
import android.app.Activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.glodon.cas.model.GlodonCas;
public class LoginActivity extends Activity {
private static Button btnLogin;
private static EditText etUsername;
private static EditText etPassword;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
btnLogin = (Button) findViewById(R.id.btnLogin);
etUsername = (EditText) findViewById(R.id.etUsername);
etPassword = (EditText) findViewById(R.id.etPassword);
btnLogin.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
new LoginTask().execute(etUsername.getText().toString(), etPassword.getText().toString());
}
});
}
public class LoginTask extends AsyncTask {
@Override
protected Boolean doInBackground(String... args) {
try {
return new GlodonCas("https://think.grandsoft.com.cn").login(args[0], args[1]);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(Boolean login_success) {
if (login_success == null) {
Toast.makeText(LoginActivity.this, R.string.network_error_tip, Toast.LENGTH_LONG).show();
return;
}
if (login_success) {
Intent intent = new Intent();
LoginActivity.this.setResult(RESULT_OK, intent);
LoginActivity.this.finish();
} else {
Toast.makeText(LoginActivity.this, R.string.login_error_tip, Toast.LENGTH_LONG).show();
}
}
}
}
整體而言,只要掌握 CAS 的「取 loginTicket → 送出帳密 → 依 303 重定向取得驗票 → 種下 cookie」流程,並把 cookie 同步進 WebView,就能在原生應用中完成無縫的單一登入體驗。
自製輪播圖元件:用自訂 View 打造廣告 Banner 輪播
閒聊兩句 前陣子公司事情不多,翻著專案裡用的廣告輪播圖,發現一直是用別人寫的第三方庫。既然手上空閒,就決定自己刻一個 Banner 元件,以後自己專案裡用起來也順手。 先
OpenCV for Android 人臉識別入門:從相冊選圖到框選臉部
在 Android 上做人臉識別,OpenCV 是常見的選擇。透過 Java API,開發者可以較快完成環境建置與基本流程,例如從相冊選圖、轉換成 OpenCV 可用的
五把雷達掃出潛伏缺陷:Eclipse 靜態分析插件實戰
如果能夠在程式碼進入版控之前,就攔下八成以上的潛在問題,那會是什麼光景?答案是:可以。Eclipse 生態系裡有一批成熟的靜態分析插件,例如 JDepend 與 Chec
Android Touch 事件傳遞機制剖析:dispatch、intercept 與 onTouchEvent
事件傳遞的三個方法 ViewGroup 子類常涉及 dispatchTouchEvent、onInterceptTouchEvent 與 onTouchEvent。dis