編輯:關於 Android 程式設計
早期 Android 內建 Apache HttpClient,是送出表單式 POST 請求最直覺的選擇。以下封裝成一個工具類,輸入 Map、編碼與網址,直接回傳回應字串。
package com.liuc;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
public class HttpPostUtil {
public static String sendHttpPost(Map<String, String> map, String encode, String path) {
// 1. 把 Map 攤平成 NameValuePair 清單
List<NameValuePair> list = new ArrayList<NameValuePair>();
if (map != null && !map.isEmpty()) {
for (Map.Entry<String, String> entry : map.entrySet()) {
list.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
}
}
try {
// 2. 封裝成表單實體,也就是請求主體
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list, encode);
HttpPost httpPost = new HttpPost(path);
httpPost.setEntity(entity);
// 3. 設定逾時(4.3 之後改用 RequestConfig)
RequestConfig requestConfig = RequestConfig.custom()
.setSocketTimeout(2000)
.setConnectTimeout(2000)
.build();
httpPost.setConfig(requestConfig);
// 4. 執行請求
// 3.x 的寫法是 new DefaultHttpClient(),4.x 之後改用 HttpClients.createDefault()
HttpClient httpClient = HttpClients.createDefault();
HttpResponse httpResponse = httpClient.execute(httpPost);
if (httpResponse.getStatusLine().getStatusCode() == 200) {
return getStringForInputStream(httpResponse.getEntity().getContent(), encode);
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return path;
}
/** 把串流讀成字串,需自行關閉 */
private static String getStringForInputStream(InputStream inputStream, String encode) {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
byte[] data = new byte[1024];
int len = 0;
String result = "";
try {
if (inputStream != null) {
while ((len = inputStream.read(data)) != -1) {
stream.write(data, 0, len);
}
result = new String(stream.toByteArray(), encode);
}
} catch (Exception e) {
// 實務上請至少記錄 log,不要靜默吞掉
}
return result;
}
}Map<String, String> params = new HashMap<String, String>();
params.put("username", "test");
params.put("page", "1");
String result = HttpPostUtil.sendHttpPost(params, "UTF-8", "https://example.com/api/login");NetworkOnMainThreadException。請用 AsyncTask、執行緒池或(更推薦的)OkHttp/Retrofit 搭配非同步回呼。org.apache.http 被標記為 uses-library 需顯式宣告,Android 6.0 更直接從 SDK 移除,必須自行打包 useLibrary 'org.apache.http.legacy' 或引入 jar。新專案請改用 HttpURLConnection 或 OkHttp。path(也就是把網址當結果回傳)是很危險的設計,呼叫端容易誤判成功;例外被靜默吞掉也讓除錯變成惡夢。建議改成拋出自訂例外或回傳帶狀態的結果物件。InputStream 未關閉會造成連線無法回收。若仍使用 HttpClient,建議用 EntityUtils.toString(entity, encode) 取代手寫讀取,它會妥善處理資源。<uses-permission android:name="android.permission.INTERNET" />,缺少時一樣是一片空白。
Android 非同步任務 AsyncTask 完整指南
AsyncTask 是 Android 早期為了解決「耗時操作不能跑在主執行緒」而提供的便捷方案。它讓背景運算與 UI 更新能用同一個類別寫完,不必自己管理執行緒與 Ha
Android系統架構全解析
一、Android的發展歷程 2003年Andy Rubin創辦Android公司;2005年Google收購Android公司;2007年成立開放手持設備聯盟(OHA)
Android 基礎控件詳解:ImageView 屬性、縮放旋轉與網絡加載
一、ImageView 是什麼 ImageView(圖像視圖)直接繼承自 View,主要功能是顯示圖片。實際上它並不限於位圖——任何 Drawable 對象都可以交給它來
Android 5.0 之 NavigationView 使用詳解
側滑導航菜單的實現方式五花八門,網上也不乏各種炫酷方案。這一篇只想安靜地講清楚一件事:Google 在 Android 5.0 之後官方推出的 NavigationVie