編輯:關於 Android 程式設計
Apache HttpClient 的 POST 寫法比 GET 更直觀:把要送出的欄位放進一個 List<NameValuePair>,包裝成 UrlEncodedFormEntity 掛到 HttpPost 上即可,不必自己拼字串。
/**
* 以 HttpClient 的 POST 方式發送請求
*
* @param username 使用者名稱
* @param password 密碼
* @return null 表示請求路徑有問題,text 為請求取得的資料
*/
public static String httpclientPost(String username, String password) {
try {
// 1. 建立客戶端
HttpClient client = new DefaultHttpClient();
// 2. 指定請求位址與方式
String path = "https://172.22.64.156:8080/0001AndroidWebService/LoginServlet";
HttpPost post = new HttpPost(path);
// 準備要提交的資料實體
List<NameValuePair> parameters = new ArrayList<NameValuePair>();
parameters.add(new BasicNameValuePair("username", username));
parameters.add(new BasicNameValuePair("password", password));
post.setEntity(new UrlEncodedFormEntity(parameters, "UTF-8"));
// 3. 送出請求
HttpResponse response = client.execute(post);
// 取得回應狀態碼
int code = response.getStatusLine().getStatusCode();
if (code == 200) {
InputStream is = response.getEntity().getContent();
String text = StreamUtil.readStream(is);
return text;
} else {
return null;
}
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
用 NameValuePair 清單組裝參數,等於把編碼工作交給 UrlEncodedFormEntity 處理,中文與特殊字元不會出問題,也不必自己算 Content-Length。這正好避開了手寫 HttpURLConnection POST 時最常見的兩個坑。
同樣地,Apache HttpClient 自 Android 6.0(API 23)起已被移出平台。若要在新專案沿用,需於 Gradle 中加入:
android {
useLibrary 'org.apache.http.legacy'
}
或改用 OkHttp,它提供了幾乎等價的表單提交能力:
OkHttpClient client = new OkHttpClient();
RequestBody body = new FormBody.Builder()
.add("username", username)
.add("password", password)
.build();
Request request = new Request.Builder()
.url(path)
.post(body)
.build();
Android 屬性動畫(Property Animation)完全解析(上):從 ObjectAnimator 到 AnimatorSet
Android 提供了三類動畫機制:View Animation、Drawable Animation 與 Property Animation。View Animati
Android 開發自學筆記(一):打造你的第一個 Hello World
Android 當道,現在學習 Android 開發還晚嗎?寫下這個問題的時間是 2014 年 6 月 15 號,而我的回答是:不晚,Android 至少還能活躍 10
App 的打磨之路(上):從單元測試、性能分析到簽名配置
前言 俗話說「磨刀不誤砍柴工」。一個優秀的產品,從一閃而過的靈感,到真正交到用戶手中,往往需要整個團隊不遺餘力地協同打磨。同理,一款出色的 App 除了核心的程式碼撰寫之
標題欄的公共抽取:兩種 BaseActivity 封裝思路與取捨
為什麼要抽標題欄 一個 App 裡絕大多數頁面都長得差不多:左邊返回鍵、中間標題、右邊一兩個操作入口。如果每個 Activity 都自己寫一份標題欄佈局,日後改配色、改高