編輯:關於 Android 程式設計
網絡請求是 Android 開發的基礎能力。本文分別用 HttpURLConnection 和 HttpClient 演示如何發送 GET 與 POST 請求。
GET 請求把參數拼接在 URL 後,開啟連接後讀取輸入流即可。注意網絡操作必須放在子線程,並透過 Handler 把結果回傳主線程更新 UI:
public void send() {
String target = "";
target = "https://192.168.1.66:8081/blog/index.jsp?content="
+ base64(content.getText().toString().trim());
URL url;
try {
url = new URL(target);
HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
InputStreamReader in = new InputStreamReader(urlConn.getInputStream());
BufferedReader buffer = new BufferedReader(in);
String inputLine = null;
while ((inputLine = buffer.readLine()) != null) {
result += inputLine + "\n";
}
in.close();
urlConn.disconnect();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
// 對字符串進行 Base64 編碼並做 URL 編碼
public String base64(String content) {
try {
content = Base64.encodeToString(content.getBytes("utf-8"), Base64.DEFAULT);
content = URLEncoder.encode(content);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return content;
}
POST 請求把參數寫入輸出流,需設置請求方式與內容類型:
public void send() {
String target = "https://192.168.1.66:8081/blog/dealPost.jsp";
URL url;
try {
url = new URL(target);
HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
urlConn.setRequestMethod("POST");
urlConn.setDoInput(true);
urlConn.setDoOutput(true);
urlConn.setUseCaches(false);
urlConn.setInstanceFollowRedirects(true);
urlConn.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
DataOutputStream out = new DataOutputStream(urlConn.getOutputStream());
String param = "nickname=" + URLEncoder.encode(nickname.getText().toString(), "utf-8")
+ "&content=" + URLEncoder.encode(content.getText().toString(), "utf-8");
out.writeBytes(param);
out.flush();
out.close();
if (urlConn.getResponseCode() == HttpURLConnection.HTTP_OK) {
InputStreamReader in = new InputStreamReader(urlConn.getInputStream());
BufferedReader buffer = new BufferedReader(in);
String inputLine = null;
while ((inputLine = buffer.readLine()) != null) {
result += inputLine + "\n";
}
in.close();
}
urlConn.disconnect();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
與 HttpURLConnection 的 GET 相比,僅 send 方法不同:
public void send() {
String target = "https://192.168.1.66:8081/blog/deal_httpclient.jsp?param=get";
HttpClient httpclient = new DefaultHttpClient();
HttpGet httpRequest = new HttpGet(target);
HttpResponse httpResponse;
try {
httpResponse = httpclient.execute(httpRequest);
if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
result = EntityUtils.toString(httpResponse.getEntity());
} else {
result = "請求失敗!";
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
同樣地,僅 send 方法不同,POST 參數封裝進 NameValuePair 列表:
public void send() {
String target = "https://192.168.1.66:8081/blog/deal_httpclient.jsp";
HttpClient httpclient = new DefaultHttpClient();
HttpPost httpRequest = new HttpPost(target);
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("param", "post"));
params.add(new BasicNameValuePair("nickname", nickname.getText().toString()));
params.add(new BasicNameValuePair("content", content.getText().toString()));
try {
httpRequest.setEntity(new UrlEncodedFormEntity(params, "utf-8"));
HttpResponse httpResponse = httpclient.execute(httpRequest);
if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
result += EntityUtils.toString(httpResponse.getEntity());
} else {
result = "請求失敗!";
}
} catch (UnsupportedEncodingException e1) {
e1.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
實踐中,GET 適合獲取數據、參數可見且長度有限;POST 適合提交敏感或大數據量內容,參數放在請求體中更安全。無論哪種方式,都要牢記把網絡請求放到子線程執行。
Android 三種菜單:OptionsMenu、ContextMenu 與 PopupMenu
Android 的菜單體系有三套,觸發方式和適用場景各不相同。下面逐一動手實作。 OptionsMenu(選項菜單) 接入步驟: 1. 覆寫 Activity 的 onC
Android Studio 中文顯示亂碼的解決方法
剛裝好 Android Studio 之後,比如匯入工程的時候,你會發現不少中文目錄或檔名顯示異常,變成一堆問號或方塊,如下圖: 原因其實很單純:Android Stu
Android 護眼燈與高相容性手電筒實作
這個範例包含兩個實用功能:護眼濾光片與手電筒。護眼燈透過懸浮視窗覆蓋螢幕,手電筒則利用 Camera 的閃光燈模式。 護眼燈 使用 WindowManager 建立全螢幕
Android 自定義日期時間選擇器:同時選擇年月日與時分
需求說明 在某些表單中,使用者需要一次選取日期與時間,例如設定開始時間、結束時間或提醒時間。若分開使用兩個選擇器,操作會較繁瑣,因此可以自定義一個整合 DatePicke