編輯:關於 Android 開發
HttpClient 是早期 Android 常見的網路請求方式,介面就兩個按鈕加一個顯示結果的文本框:一個負責發 GET,一個負責彈出登入框發 POST。雖然它在後續版本被標記為廢棄,但理解它的四步流程,對看懂 HTTP 請求的本質很有幫助。
GET 請求的標準四步:
1、建立 HttpClient 物件:HttpClient httpclient = new DefaultHttpClient();
2、建立代表請求的 HttpGet:HttpGet httpget = new HttpGet("https://www.baidu.com");
3、執行請求並取得回應物件 HttpResponse:httpclient.execute(httpget);
4、從回應中取出實體 HttpEntity:httpresponse.getEntity(),再從中讀內容。
public class HttpClientDemo extends Activity {
private TextView response;
private HttpClient httpclient;
private Handler handler = new Handler() {
public void handleMessage(Message msg) {
if (msg.what == 0x123) {
response.append(msg.obj.toString() + "\n");
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_http_client);
httpclient = new DefaultHttpClient();
response = findViewById(R.id.response);
}
/** 發送 GET 請求 */
public void accessSecret(View v) {
response.setText("");
new Thread() {
public void run() {
HttpGet httpget = new HttpGet("https://localhost:8080/foo/secret.jsp");
try {
HttpResponse httpresponse = httpclient.execute(httpget);
HttpEntity entity = httpresponse.getEntity();
if (entity != null) {
BufferedReader br = new BufferedReader(
new InputStreamReader(entity.getContent()));
String line;
while ((line = br.readLine()) != null) {
Message msg = new Message();
msg.what = 0x123;
msg.obj = line;
handler.sendMessage(msg); // 交回 UI 執行緒更新
}
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}.start();
}
/** 彈出登入框並發送 POST 請求 */
public void showLogin(View v) {
final View loginDialog = getLayoutInflater().inflate(R.layout.login, null);
new AlertDialog.Builder(this)
.setTitle("登錄系統")
.setView(loginDialog)
.setPositiveButton("確定", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
final String name = ((EditText) loginDialog.findViewById(R.id.name))
.getText().toString();
final String pass = ((EditText) loginDialog.findViewById(R.id.pass))
.getText().toString();
new Thread() {
public void run() {
try {
HttpPost httppost = new HttpPost(
"https://localhost:8080/foo/login.jsp");
// 把參數封裝成名稱值對
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("name", name));
params.add(new BasicNameValuePair("pass", pass));
httppost.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
HttpResponse httpresponse = httpclient.execute(httppost);
if (httpresponse.getStatusLine().getStatusCode() == 200) {
String msg = EntityUtils.toString(httpresponse.getEntity());
Toast.makeText(HttpClientDemo.this, msg,
Toast.LENGTH_LONG).show();
}
} catch (ParseException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}.start();
}
})
.setNegativeButton("取消", null)
.show();
}
}
幾點實務提醒:
· 網路請求一定要放在子執行緒,主執行緒做網路操作會直接拋 NetworkOnMainThreadException。
· 回主線更新 UI 有正規做法,用 Handler 是其一,也可以改用 runOnUiThread 或後來的 AsyncTask/RxJava。
· 上例中在子線寫 Looper.prepare()/loop() 去彈 Toast 並不是好習慣,容易把線卡住,建議一律交回主執行緒處理。
· 常見狀態碼:200 成功、301/302 重新導向、404 找不到資源、500 系列為伺服器端錯誤。
· 新專案請直接使用 OkHttp 或 Retrofit,並記得在清單中申請 android.permission.INTERNET 權限。
box-flex 彈性可伸縮盒模型筆記
box-flex 彈性可伸縮盒模型筆記在移動端開發中,Flexbox 是一種非常實用的布局方案。它能夠在未知或動態容器內,讓子元素按照需要伸縮、排列與對齊。相比傳統的 f
Android EditText 密碼框明文與密文切換的兩種實現方式
Android EditText 密碼框明文與密文切換的兩種實現 在做登錄界面時,密碼框需要支持「明文/密文」的即時切換,這是很實用的交互細節。下面我整理了布局文件以及
3D圖片採集與展示實戰:SurfaceView自適應Camera、錄屏抽幀全流程
3D圖片採集與展示實戰:SurfaceView自適應Camera、錄屏抽幀全流程 最近在做一個3D圖片採集與展示的功能。 主要功能為:自定義Camera(Google已
自訂 ZXing 二維碼掃描介面與取景框修正
自訂 ZXing 二維碼掃描介面與取景框修正ZXing 是 Android 中常見的二維碼掃描解決方案,但預設掃描介面未必符合每個應用程式的視覺需求。若要自訂掃描畫面,通