編輯:關於 Android 程式設計
做 Android 網絡請求,常見有幾條路:原生 HttpURLConnection、Apache HttpClient,以及成熟的第三方框架。下面按這三類分別給出可運行的寫法,並附上最簡陋的 Java Web 後端作為對照,方便你把整條鏈路跑通。
官方推薦的做法。它的使用步驟很清晰:
1. 呼叫 URL.openConnection() 並轉型為 HttpURLConnection;
2. 準備請求:主要屬性是其 URI,請求頭可攜帶認證資訊、期望的內容類型、Session Cookie 等;
3. 如有請求體,需先 setDoOutput(true),然後向 getOutputStream() 寫資料;
4. 讀取響應:響應頭包含內容類型、長度、修改時間等中繼資料,響應體從 getInputStream() 讀;無 body 時返回空串流;
5. 讀完後呼叫 disconnect() 釋放資源,使其可被關閉或複用。
最簡要的 GET:
URL url = new URL("https://www.android.com/");
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
try {
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
readStream(in);
} finally {
urlConnection.disconnect();
}
幾個值得記住的特性:呼叫 URL.openConnection() 時若 scheme 是 https,會返回 HttpsURLConnection,可以自定義 HostnameVerifier 與 SSLSocketFactory;它會自動跟隨最多五次 HTTP 重定向(但不處理 HTTPS 與 HTTP 互跳);出錯時 getInputStream() 會拋 IOException,此時可用 getErrorStream() 讀取錯誤響應體,響應頭照常用 getHeaderFields() 讀。
上傳資料時,若已知 body 長度,建議呼叫 setFixedLengthStreamingMode(int);長度未知則用 setChunkedStreamingMode(int)。否則 HttpURLConnection 會先把整個請求體緩存進記憶體再發送,浪費堆空間並增加延遲。
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
try {
urlConnection.setDoOutput(true);
urlConnection.setChunkedStreamingMode(0);
OutputStream out = new BufferedOutputStream(urlConnection.getOutputStream());
writeStream(out);
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
readStream(in);
} finally {
urlConnection.disconnect();
}
public class NetUtils1 {
private static final String TAG = "NetUtils1";
private static final String URL =
"https://10.10.39.11:8080/Androiddata/Servletdata";
/** POST 登陸 */
public static String loginOfPost(String userName, String password) {
HttpURLConnection conn = null;
try {
conn = (HttpURLConnection) new URL(URL).openConnection();
conn.setRequestMethod("POST");
conn.setConnectTimeout(10000);
conn.setReadTimeout(5000);
conn.setDoOutput(true); // 允許輸出,否則無法寫入請求體
String data = "username=" + userName + "&password=" + password;
OutputStream out = conn.getOutputStream();
out.write(data.getBytes());
out.flush();
out.close();
if (conn.getResponseCode() == 200) {
return getStringFromInputStream(conn.getInputStream());
} else {
Log.i(TAG, "訪問失敗" + conn.getResponseCode());
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (conn != null) conn.disconnect();
}
return null;
}
/** GET 登陸 */
public static String loginOfGet(String userName, String password) {
HttpURLConnection conn = null;
try {
String data = "username=" + URLEncoder.encode(userName, "utf-8")
+ "&password=" + URLEncoder.encode(password, "UTF-8");
conn = (HttpURLConnection) new URL(URL + "?" + data).openConnection();
conn.setConnectTimeout(10000);
conn.setReadTimeout(5000);
if (conn.getResponseCode() == 200) {
return getStringFromInputStream(conn.getInputStream());
} else {
Log.i(TAG, "訪問失敗" + conn.getResponseCode());
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (conn != null) conn.disconnect();
}
return null;
}
/** 流轉字串 */
private static String getStringFromInputStream(InputStream is) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len;
while ((len = is.read(buffer)) != -1) {
baos.write(buffer, 0, len);
}
is.close();
String html = baos.toString();
baos.close();
return html;
}
}
調用時記得放到子線程,再切回主線程更新 UI:
public void doGet(View v) {
final String userName = etUserName.getText().toString();
final String password = etPassword.getText().toString();
new Thread(() -> {
final String state = NetUtils1.loginOfGet(userName, password);
runOnUiThread(() ->
Toast.makeText(MainActivity.this, "返回:" + state,
Toast.LENGTH_SHORT).show());
}).start();
}
public class NetUtils2 {
private static final String TAG = "NetUtils222";
private static final String URL =
"https://10.10.39.11:8080/Androiddata/Servletdata";
/** POST */
public static String loginOfPost(String userName, String password) {
HttpClient client = null;
try {
client = new DefaultHttpClient();
HttpPost post = new HttpPost(URL);
List<NameValuePair> parameters = new ArrayList<>();
parameters.add(new BasicNameValuePair("username", userName));
parameters.add(new BasicNameValuePair("password", password));
// 必須指定字元集,否則服務端取到的中文會亂碼
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(parameters, "utf-8");
post.setEntity(entity);
HttpResponse response = client.execute(post);
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode == 200) {
return getStringFromInputStream(response.getEntity().getContent());
} else {
Log.i(TAG, "請求失敗" + statusCode);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (client != null) client.getConnectionManager().shutdown();
}
return null;
}
/** GET */
public static String loginOfGet(String userName, String password) {
HttpClient client = null;
try {
client = new DefaultHttpClient();
String data = "username=" + userName + "&password=" + password;
HttpGet get = new HttpGet(URL + "?" + data);
HttpResponse response = client.execute(get);
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode == 200) {
return getStringFromInputStream(response.getEntity().getContent());
} else {
Log.i(TAG, "請求失敗" + statusCode);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (client != null) client.getConnectionManager().shutdown();
}
return null;
}
}
需要說明的是,Apache HttpClient 從 Android 5.1 起已被標記為廢棄,後續版本逐步移除,新專案不建議再使用,這裡保留是為了理解歷史程式碼。
框架化之後,GET / POST 與回呼都變得非常輕量:
public void doGet(View v) {
String userName = etUserName.getText().toString();
String password = etPassword.getText().toString();
AsyncHttpClient client = new AsyncHttpClient();
try {
String data = "username=" + URLEncoder.encode(userName, "UTF-8")
+ "&password=" + URLEncoder.encode(password, "UTF-8");
client.get(URL + "?" + data, new MyResponseHandler());
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
public void doPost(View view) {
AsyncHttpClient client = new AsyncHttpClient();
RequestParams params = new RequestParams();
params.put("username", etUserName.getText().toString());
params.put("password", etPassword.getText().toString());
client.post(URL, params, new MyResponseHandler());
}
class MyResponseHandler extends AsyncHttpResponseHandler {
@Override
public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
Toast.makeText(MainActivity2.this,
"成功: statusCode: " + statusCode
+ ", body: " + new String(responseBody),
Toast.LENGTH_LONG).show();
}
@Override
public void onFailure(int statusCode, Header[] headers,
byte[] responseBody, Throwable error) {
Toast.makeText(MainActivity2.this, "失敗: statusCode: " + statusCode,
Toast.LENGTH_LONG).show();
}
}
它自帶線程池與二進制/字串/JSON 等預置 ResponseHandler,並支援重試與 Cookie 持久化,對於快速搭原型很方便。
一個 Servlet 就夠了:
@WebServlet(name = "Servletdata", urlPatterns = "/Servletdata")
public class Servletdata extends HttpServlet {
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=utf-8");
request.setCharacterEncoding("UTF-8");
String username = request.getParameter("username");
String password = request.getParameter("password");
if ("sdingba".equals(username) && "123".equals(password)) {
response.getOutputStream().write("success".getBytes());
} else {
response.getOutputStream().write("error".getBytes());
}
}
}
整條鏈路跑通之後,實際專案裡通常會再往上封一層:統一處理狀態碼與業務錯誤碼、加上攔截器做簽名與 token 注入、用 JSON 而非自由文本作為數據格式。關於 HTTP 通信,RxJava + Retrofit、OkHttp、Volley 等都是不錯的選擇,值的投入時間去深入了解。
Android AppCompatActivity 與 Toolbar 整合指南
從 AppCompatActivity 開始在 Android 5.0 之後,Toolbar 逐漸取代 ActionBar,而 AppCompatActivity 也成為
告別制式圖標!手機端自訂APP圖標教學
想自訂APP圖標,需Root後用RE檔案管理器、X-plore與Photoshop手機版。先從APK的res/drawable-hdpi取出icon.png,編輯後存成P
AsyncTask 異步任務:用法、源碼原理與實踐陷阱
搞懂 Android 的緩存機制之後,我打算自己動手寫一個基於 LruCache 與 DiskLruCache 二級緩存的輕量級圖片請求框架。搭框架時卡在了一個問題上:下
Android ListView 下拉刷新完整實作
下拉刷新的基本結構下拉刷新是列表頁常見的互動。實作時,通常會自訂 ListView,並在頂部加入一個隱藏的下拉刷新表頭。當使用者用手指下拉時,表頭會逐漸顯示;放開後,若達