編輯:關於 Android 程式設計
下面用一個登入的小範例,說明 Android 端如何以 HttpClient 分別用 GET 與 POST 呼叫同一支 Servlet。兩種方式的差別只在參數傳遞:GET 把帳密拼在網址後面,POST 則用 NameValuePair 清單打包成表單實體。
public class MainActivity3 extends ActionBarActivity {
private EditText et_userName;
private EditText et_password;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
et_userName = (EditText) findViewById(R.id.et_userName);
et_password = (EditText) findViewById(R.id.et_password);
}
public void login(View view) {
String str = et_userName.getText().toString();
try {
// 帳號可能含中文或特殊字元,先編碼
str = URLEncoder.encode(str, "utf-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
final String userName = str;
final String password = et_password.getText().toString();
// 網路操作必須放在子執行緒
new Thread(new Runnable() {
@Override
public void run() {
try {
final boolean isSuccess = loginByPost(userName, password);
// 若改用 loginByGet(userName, password) 亦可
// runOnUiThread 會把操作排回主執行緒執行
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(MainActivity3.this,
isSuccess ? "成功了!!!" : "失敗了!!!",
Toast.LENGTH_SHORT).show();
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
}
/**
* HttpClient 以 GET 方式存取伺服器
*/
private Boolean loginByGet(String userName, String password) throws Exception {
String url = "https://192.168.1.140:8080/Login/servlet/Login";
String data = "?userName=" + userName + "&password=" + password;
HttpClient client = new DefaultHttpClient();
HttpGet get = new HttpGet(url + data);
HttpResponse response = client.execute(get);
int code = response.getStatusLine().getStatusCode();
if (code == 200) {
InputStream is = response.getEntity().getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
String text = reader.readLine();
reader.close();
is.close();
return "SUCCESS".equals(text);
}
client.getConnectionManager().shutdown();
return false;
}
/**
* HttpClient 以 POST 方式存取伺服器
*/
boolean loginByPost(String userName, String password) throws Exception {
String url = "https://192.168.1.140:8080/Login/servlet/Login";
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(url);
// 以表單形式送出參數
List<NameValuePair> list = new ArrayList<>();
list.add(new BasicNameValuePair("userName", userName));
list.add(new BasicNameValuePair("password", password));
post.setEntity(new UrlEncodedFormEntity(list));
HttpResponse response = client.execute(post);
int code = response.getStatusLine().getStatusCode();
if (code == 200) {
InputStream is = response.getEntity().getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
String text = reader.readLine();
reader.close();
is.close();
return "SUCCESS".equals(text);
}
client.getConnectionManager().shutdown();
return false;
}
<uses-permission android:name="android.permission.INTERNET" />
另外提醒兩點:一是 POST 比 GET 適合傳送帳密,因為 GET 的參數會留在伺服器與代理的存取記錄裡;二是 Apache HttpClient 在較新的 Android 版本已被標記為 deprecated,新專案建議改用 HttpURLConnection 或 OkHttp,並記得連線逾時要設定,避免執行緒被無限期佔用。
Android 中 GET 與 POST 的三種提交方式整理
在 Android 開發中,向伺服器提交資料最常見的方式就是 GET 與 POST。兩者的差異主要在安全性、長度限制與資料結構。GET 會把參數附在網址後方,較容易暴露,
Android 菜鳥筆記(3):Activity 之間的切換與數據傳遞
在 Android 中,每個 Activity 通常對應屏幕上的的一個界面(窗口級別的 Activity 除外),因此手機上兩個界面之間的切換,本質上就是 Activit
Android Maven 多 dex 打包設定
問題背景當專案方法數超過 65536 限制時,可使用 MultiDex。若使用 Maven,可透過 android-maven-plugin 設定多 dex 打包。App
Android ApiDemos 導入與運行步驟
Android SDK 自帶了大量示例,存放在 android-sdk/samples 目錄下,涵蓋了 Android 平台主要 API 的用法,是一份不可多得的學習資料