編輯:關於 Android 程式設計
做 Android 開發,網絡數據的抓取與提交是家常便飯。一個簡單的口訣可以幫你快速定位場景:獲取數據用 GET 請求,而新增、刪除、修改、查詢等需要改動服務端數據的操作則用 POST 請求。

本例用 HttpURLConnection 完成兩種請求,並借助 AsyncTask 把網絡操作放到子線程,避免阻塞主線程(UI 線程)。GET 直接把參數拼在 URL 後邊;POST 則把參數寫入輸出流,並通過 setRequestMethod("POST") 與適當的請求頭來告知服務端。
點擊「查詢(GET 方法)」按鈕時拼接參數發起 GET;點擊「查詢(POST 方法)」時把參數放進數組交給 POST 任務處理。
public class HttpActivity extends AppCompatActivity {
public EditText et;
private Button search;
private Button search1;
private TextView show;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_http);
et = (EditText) findViewById(R.id.et);
search = (Button) findViewById(R.id.search);
search1 = (Button) findViewById(R.id.search1);
show = (TextView) findViewById(R.id.show);
search.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String url = "https://192.168.1.48:8080/HttpTest/index.jsp?option=getUser&uName=jerehedu";
new MyGetJob().execute(url);
}
});
search1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String[] arg = new String[2];
arg[0] = "https://192.168.1.48:8080/HttpTest/index.jsp";
arg[1] = "option=getUser&uName=jerehedu";
new MyPostJob1().execute(arg);
}
});
}
// POST 異步任務
private class MyPostJob1 extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... strings) {
HttpURLConnection con = null;
InputStream is = null;
StringBuilder sbd = new StringBuilder();
try {
URL url = new URL(strings[0]);
con = (HttpURLConnection) url.openConnection();
con.setConnectTimeout(5 * 1000);
con.setReadTimeout(5 * 1000);
con.setRequestMethod("POST");
con.setDoInput(true);
con.setDoOutput(true);
con.setUseCaches(false);
con.setRequestProperty("Charset", "UTF-8");
con.setRequestProperty("Content-type", "application/x-www-form-urlencoded");
// params 形如:option=getUser&uName=jerehedu
String params = strings[1];
OutputStream os = con.getOutputStream();
os.write(params.getBytes()); // 數據傳輸流
os.flush();
os.close();
if (con.getResponseCode() == 200) {
is = con.getInputStream();
int next = 0;
byte[] b = new byte[1024];
while ((next = is.read(b)) > 0) {
sbd.append(new String(b, 0, next));
}
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (is != null) {
try { is.close(); } catch (IOException e) { e.printStackTrace(); }
if (con != null) { con.disconnect(); }
}
}
return sbd.toString();
}
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
show.setText("POST請求結果:" + s);
}
}
// GET 異步任務
private class MyGetJob extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... strings) {
HttpURLConnection con = null;
InputStream is = null;
StringBuilder sbd = new StringBuilder();
try {
URL url = new URL(strings[0]);
con = (HttpURLConnection) url.openConnection();
con.setConnectTimeout(5 * 1000);
con.setReadTimeout(5 * 1000);
// 200 成功 / 404 未找到 / 500 服務端錯誤
if (con.getResponseCode() == 200) {
is = con.getInputStream();
int next = 0;
byte[] bt = new byte[1024];
while ((next = is.read(bt)) > 0) {
sbd.append(new String(bt, 0, next));
}
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (is != null) {
try { is.close(); } catch (IOException e) { e.printStackTrace(); }
if (con != null) { con.disconnect(); }
}
}
return sbd.toString();
}
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
show.setText(s);
}
}
}
關於 AsyncTask 的三個泛型參數需要牢記:第一個參數會傳入 doInBackground 方法,第三個參數指定 doInBackground 的返回值類型,而這個返回值會被 onPostExecute 接收並在 UI 線程中處理。
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:tools="https://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.jreduch07.HttpActivity">
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="@+id/et"
android:layout_alignParentStart="true"
android:layout_alignTop="@+id/et"
android:text="姓名!"
android:textSize="20dp" />
<EditText
android:id="@+id/et"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="@+id/search"
android:layout_centerHorizontal="true"
android:hint="請輸入要查找姓名" />
<Button
android:id="@+id/search"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_alignParentTop="true"
android:text="查詢(GET方法)" />
<Button
android:id="@+id/search1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_below="@+id/et"
android:text="查詢(POST方法)" />
<TextView
android:id="@+id/show"
android:layout_width="match_parent"
android:layout_height="150dp"
android:layout_alignParentStart="true"
android:layout_below="@+id/search1"
android:background="#fff30d"
android:text="查詢結果:"
android:textSize="30sp" />
</RelativeLayout>



GET 與 POST 在本質上都是基於 HttpURLConnection 的網絡請求,差別在於:GET 把參數附在 URL 之後,讀取輸入流即可拿到結果;POST 需要設置請求方法與 Content-Type 請求頭,並把參數寫入輸出流。同時,別忘了 network 操作一定要放在子線程(這裡用 AsyncTask 封裝),並在 onPostExecute 中回到主線程更新界面。此外,記得在清單文件中申請網絡訪問權限。
Android 設計模式之單例模式:以 InputMethodManager 為例
單例模式大概是 GOF 二十三是中最容易理解的一個。它與其他模式耦合很少,只管一件事:控制自己的實例數量唯一,而不去操心該為使用者生產什麼樣的對象。這種「只管一攤」的克制
Android JNI 學習筆記(四):型別映射與在 Native 層反過來呼叫 Java
1. 前言 前面幾篇我們走完了 JNI 開發的基本流程、動態註冊 native 函數,以及編譯相關文件的寫法。但只到這裡還不夠——今天要補上兩塊拼圖:Java 與 JNI
Android 遊戲開發:按鍵事件的響應處理
在遊戲開發中,按鍵事件的響應處理是一項基礎而重要的技能。本文將詳細說明 onKeyDown 與 onKeyUp 兩個方法的原理與用法,並透過範例演示如何在自定義 View
Android 屬性動畫完全指南:從 XML 到代碼,再到 Keyframe 進階用法
相比補間動畫,屬性動畫(Property Animation)是更徹底的一套方案,它的兩個核心特點是: 改變的是物件真實的屬性值,而不只是畫面上的變換。 作用範圍不限於