編輯:關於 Android 開發
這篇把最基礎的四種 HTTP 請求寫法放在一起對照:HttpURLConnection 的 GET 與 POST,以及 HttpClient 的 GET 與 POST。同一件事寫四遍,差異就很清楚了。
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:tools="https://schemas.android.com/tools"
android:layout_width="match_parent"
android:orientation="vertical"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<EditText
android:id="@+id/et_username"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="請輸入用戶名"
android:text="張三" />
<EditText
android:id="@+id/et_password"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="請輸入密碼"
android:inputType="textPassword" />
<Button
android:onClick="myGetData"
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="登陸" />
</LinearLayout>
重點在於網路請求必須放在子執行緒,完成後再切回主執行緒更新 UI:
package com.example.getdata;
import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends Activity {
private EditText et_username;
private EditText et_password;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
et_username = (EditText) findViewById(R.id.et_username);
et_password = (EditText) findViewById(R.id.et_password);
}
public void myGetData(View view) {
final String username = et_username.getText().toString().trim();
final String password = et_password.getText().toString().trim();
System.out.println("username:" + username);
System.out.println("password:" + password);
new Thread() {
public void run() {
// 四種寫法擇一,切換註解即可對照
// final String result = LoginService.loginByGet(username, password);
// final String result = LoginService.loginByPost(username, password);
// final String result = LoginService.loginByClientGet(username, password);
final String result = LoginService.loginByClientPost(username, password);
if (result != null) {
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(MainActivity.this, result, 0).show();
}
});
} else {
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(MainActivity.this, "請求不成功!", 0).show();
}
});
}
}
}.start();
}
}
package com.example.getdata.service;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import com.example.getdata.utils.StreamTools;
/* 注意事項:送出請求時若含有中文,記得轉成對應編碼 */
public class LoginService {
/** 寫法一:HttpURLConnection + GET */
public static String loginByGet(String username, String password) {
try {
String path = "https://192.168.1.100/android/index.php?username="
+ URLEncoder.encode(username, "utf-8")
+ "&password=" + password;
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setReadTimeout(5000);
int code = conn.getResponseCode();
if (code == 200) {
InputStream is = conn.getInputStream();
return StreamTools.readInputStream(is);
} else {
return null;
}
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/** 寫法二:HttpURLConnection + POST */
public static String loginByPost(String username, String password) {
String path = "https://192.168.1.101/android/index.php";
try {
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setReadTimeout(5000);
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
String data = "username=" + URLEncoder.encode(username, "utf-8")
+ "&password=" + password;
conn.setRequestProperty("Content-Length", data.length() + "");
conn.setDoOutput(true); // 允許對外寫入資料
OutputStream os = conn.getOutputStream();
os.write(data.getBytes());
int code = conn.getResponseCode();
if (code == 200) {
InputStream is = conn.getInputStream();
return StreamTools.readInputStream(is);
} else {
return null;
}
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/** 寫法三:HttpClient + GET */
public static String loginByClientGet(String username, String password) {
try {
HttpClient client = new DefaultHttpClient(); // 開一個「瀏覽器」
String path = "https://192.168.1.101/android/index.php?username="
+ URLEncoder.encode(username, "utf-8")
+ "&password=" + password;
HttpGet httpGet = new HttpGet(path);
HttpResponse response = client.execute(httpGet); // 按下 Enter
int code = response.getStatusLine().getStatusCode();
if (code == 200) {
InputStream is = response.getEntity().getContent();
return StreamTools.readInputStream(is);
} else {
return null;
}
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/** 寫法四:HttpClient + POST */
public static String loginByClientPost(String username, String password) {
try {
HttpClient client = new DefaultHttpClient();
String path = "https://192.168.1.101/android/index.php";
HttpPost httpPost = new HttpPost(path);
// 組裝要提交的參數
List<NameValuePair> parameters = new ArrayList<NameValuePair>();
parameters.add(new BasicNameValuePair("username", username));
parameters.add(new BasicNameValuePair("password", password));
httpPost.setEntity(new UrlEncodedFormEntity(parameters, "utf-8"));
HttpResponse response = client.execute(httpPost);
int code = response.getStatusLine().getStatusCode();
if (code == 200) {
InputStream is = response.getEntity().getContent();
return StreamTools.readInputStream(is);
} else {
return null;
}
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
}
package com.example.getdata.utils;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
public class StreamTools {
/** 功能:把 InputStream 轉為 String */
public static String readInputStream(InputStream is) {
try {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int len = 0;
byte[] buffer = new byte[1024];
while ((len = is.read(buffer)) != -1) {
baos.write(buffer, 0, len);
}
baos.close();
is.close();
byte[] result = baos.toByteArray();
return new String(result);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
}
<uses-permission android:name="android.permission.INTERNET"/>
一般來說子執行緒無法直接改動 UI,但這裡用 runOnUiThread 把 Toast 丟回主執行緒,所以能正常顯示,而不必改用 Handler 發送消息。
要注意的是,這四種寫法在「等待回應」這一步都是同步阻塞的——差別只在 API 風格。真正該記住的觀念是:無論用哪一種,都不能在主執行緒呼叫,否則在 Android 4.0 之後會直接拋出 NetworkOnMainThreadException。此外,Apache HttpClient 自 API 23 起已被移除,新專案請直接使用 HttpURLConnection,或改用 OkHttp 這類現代化的 HTTP 客戶端。
Android Studio 項目提交與更新到 GitHub 的完整步驟
Android Studio 項目提交與更新到 GitHub 的完整步驟 使用 Android Studio 開發時,若想把專案同步到 GitHub,不必總是依賴命令列。
Android 效能分析入門:Traceview 介面解讀與追蹤日誌實作
Traceview 是什麼 Traceview 是執行日誌的圖形化檢視器,資料來源是透過 Debug 類別記錄的方法追蹤。它能幫你看清楚一段時間內每個函式被呼叫幾次、各自
在 Android Studio 中配置 OpenCV 3.1 的完整教學
先到官網(https://opencv.org/)下載 OpenCV for Android 並解壓。由於網路因素,之前幾次下載都相當緩慢甚至中斷,後來某次意外順利完成。
Android 自定義控制項實作刮刮樂效果
Android 自定義控制項實作刮刮樂效果刮刮樂效果的核心是「覆蓋層擦除」。實作時可建立一個自訂 RelativeLayout 作為彩票檢視,底層放置獎勵內容,上層放置可