Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 網絡編程入門:從抓取 HTML 到與 JavaWeb 服務端交互

編輯:關於 Android 程式設計

本文整理 Android 下的網絡通信基礎,涵蓋四個由淺入深的主題:

1. Android 網絡編程初識;

2. 實現 HTML 源碼查看器;

3. 實現網絡圖片加載與本地緩存;

4. 與服務器上的 JavaWeb 項目交互(GET / POST / HttpClient)。


一、網絡編程初識

手機終端作為客戶端向服務器發送 HTTP 請求;請求成功時響應碼為 200,服務器返回處理後的數據。正式項目中通常使用 JSON 約定格式,而不是沒有規範的自由文本。

最重要的一條注意事項:從 Android 4.0 開始,網絡操作不能寫在主線程。除了會直接拋 NetworkOnMainThreadException 導致崩潰,更根本的原因是主線程一旦阻塞,界面就停止刷新、無法響應任何操作,體驗極差。正確做法是把網絡部分寫在子線程,再透過 Handler 把結果送回主線程更新 UI。


二、HTML 源文件查看器

public class MainActivity extends Activity {
    private Handler handler;
    private TextView tv;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        tv = findViewById(R.id.tv);

        handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                tv.setText((String) msg.obj);
            }
        };
    }

    public void click(View view) {
        final String path = "https://192.168.1.109:8080/baidu.html";
        new Thread(() -> {
            try {
                URL url = new URL(path);
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                conn.setRequestMethod("GET");
                conn.setConnectTimeout(8000);
                conn.setReadTimeout(8000);
                conn.connect();

                if (conn.getResponseCode() == 200) {
                    InputStream is = conn.getInputStream();
                    String text = StreamTool.getTextFromStream(is);
                    Message msg = handler.obtainMessage();
                    msg.obj = text;
                    handler.sendMessage(msg);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }).start();
    }
}

核心就是把服務器返回的流讀成字串,再交給 Handler:

InputStream is = conn.getInputStream();
String text = StreamTool.getTextFromStream(is);
Message msg = handler.obtainMessage();
msg.obj = text;
handler.sendMessage(msg);

順手解決亂碼

亂碼的根因是服務端與客戶端使用的編碼表不一致。封裝一個工具類統一處理:

public class StreamTool {
    public static String getTextFromStream(InputStream is) {
        byte[] buffer = new byte[1024];
        int len;
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        try {
            while ((len = is.read(buffer)) != -1) {
                bos.write(buffer, 0, len);
            }
            return new String(bos.toByteArray());
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "";
    }
}

三、網絡圖片加載與緩存

幾個必須掌握的知識點:4.0 以上的編程規範(不能在主線程做網絡操作);子線程中不能直接操作 UI,否則會拋 Can't create handler inside thread that has not called Looper.prepare();消息隊列機制——主線程啟動時就建立了 Looper 與 MessageQueue,Handler 發送的消息會被輪檢處理。

public class MainActivity extends Activity {
    private ImageView iv;
    private Bitmap bm;

    @SuppressLint("HandlerLeak")
    Handler handler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            switch (msg.what) {
                case 1:
                    iv = findViewById(R.id.iv);
                    iv.setImageBitmap((Bitmap) msg.obj);
                    break;
                case 2:
                    Toast.makeText(MainActivity.this, "加載視圖失敗",
                            Toast.LENGTH_SHORT).show();
                    break;
            }
        }
    };

    public void clickload(View view) {
        final String path = "https://192.168.2.197:8080/img/e.jpg";
        final File file = new File(getCacheDir(), getFileNameFromPath(path));

        if (file.exists()) {
            // 命中緩存,直接解碼展示
            bm = BitmapFactory.decodeFile(file.getAbsolutePath());
            Message msg = new Message();
            msg.obj = bm;
            msg.what = 1;
            handler.sendMessage(msg);
        } else {
            new Thread(() -> {
                try {
                    URL url = new URL(path);
                    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                    conn.setRequestMethod("GET");
                    conn.setConnectTimeout(8000);
                    conn.setReadTimeout(8000);
                    conn.connect();

                    if (conn.getResponseCode() == 200) {
                        InputStream is = conn.getInputStream();
                        // 邊讀邊寫,複用同一塊緩存
                        byte[] buffer = new byte[1024];
                        int len;
                        FileOutputStream fos = new FileOutputStream(file);
                        while ((len = is.read(buffer)) != -1) {
                            fos.write(buffer, 0, len);
                        }
                        fos.close();

                        bm = BitmapFactory.decodeFile(file.getAbsolutePath());
                        Message msg = new Message();
                        msg.obj = bm;
                        msg.what = 1;
                        handler.sendMessage(msg);
                    } else {
                        handler.sendEmptyMessage(2);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }).start();
        }
    }

    public String getFileNameFromPath(String path) {
        return path.substring(path.lastIndexOf("/") + 1);
    }
}

這裡有個實務細節值得留意:流一旦讀完就取不到數據了,所以註釋裡那種「先 decodeStream 再緩存」的順序是錯的。另外真實項目中緩存還需要考慮過期策略、斷點續傳與內存緩存二級結構。


四、與 JavaWeb 項目交互

4.1 GET 方式提交

服務端:

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    request.setCharacterEncoding("utf-8");
    response.setContentType("text/html;charset=utf-8");

    String username = request.getParameter("username");
    String password = request.getParameter("password");
    // 解掉 GET 傳參的 ISO-8859-1 亂碼
    username = new String(username.getBytes("ISO-8859-1"), "utf-8").trim();
    password = new String(password.getBytes("ISO-8859-1"), "utf-8").trim();

    if ("admin".equalsIgnoreCase(username)) {
        response.getWriter().print("登陸成功");
    } else {
        response.getWriter().print("登陸失敗");
    }
}

客戶端:

public void login(View view) {
    String username = et_username.getText().toString().trim();
    String password = et_password.getText().toString().trim();

    new Thread(() -> {
        try {
            String path = "https://192.168.1.105:8080/AndroidWebServerDemo/Login"
                    + "?username=" + URLEncoder.encode(username, "utf-8")
                    + "&password=" + URLEncoder.encode(password, "utf-8");
            HttpURLConnection conn =
                    (HttpURLConnection) new URL(path).openConnection();
            conn.setConnectTimeout(8000);
            conn.setReadTimeout(8000);
            conn.setRequestMethod("GET");
            conn.connect();

            if (conn.getResponseCode() == 200) {
                String text = Tools.getTextFromStream(conn.getInputStream());
                Message msg = new Message();
                msg.obj = text;
                msg.what = 1;
                handler.sendMessage(msg);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }).start();
}

4.2 POST 方式提交

服務端的差別僅在於不再需要 ISO-8859-1 轉碼:

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    request.setCharacterEncoding("utf-8");
    response.setContentType("text/html;charset=utf-8");
    // 其餘邏輯同 doGet
}

客戶端需要主動打開輸出流並寫入請求體:

conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
String content_text = "username=" + URLEncoder.encode(username, "utf-8")
        + "&password=" + URLEncoder.encode(password, "utf-8");
conn.setRequestProperty("Content-Length", content_text.length() + "");
conn.setDoOutput(true);

OutputStream os = conn.getOutputStream();
os.write(content_text.getBytes());
conn.connect();

if (conn.getResponseCode() == 200) {
    String text = Tools.getTextFromStream(conn.getInputStream());
    // 回主線程刷新
}

POST 的優勢在於參數不暴露在 URL 上、長度不受限制,提交較長文本或批量數據時更合適。

4.3 HttpClient 版本

// GET
HttpClient client = new DefaultHttpClient();
HttpGet get = new HttpGet(path);
HttpResponse response = client.execute(get);
if (response.getStatusLine().getStatusCode() == 200) {
    String text = Tools.getTextFromStream(response.getEntity().getContent());
}

// POST
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(path);
List<NameValuePair> parameters = new ArrayList<>();
parameters.add(new BasicNameValuePair("username", username));
parameters.add(new BasicNameValuePair("password", password));
post.setEntity(new UrlEncodedFormEntity(parameters, "utf-8"));
HttpResponse response = client.execute(post);
if (response.getStatusLine().getStatusCode() == 200) {
    String text = Tools.getTextFromStream(response.getEntity().getContent());
}

寫法確實比原生平舖直敘要簡潔,但需要提醒:HttpClient 在 Android 5.1 之後已被廢棄並在後續版本移除,學習階段理解原理即可,實際開發請使用 OkHttp、Retrofit 或 HttpURLConnection。

把這四節串起來看,Android 網絡編程的骨架其實就三件事:線程切換(子線程請求、主線程刷新)、協議細節(請求方法、請求頭、編碼)、數據解析(流轉字串或 JSON)。剩下的差異,多半在框架封裝的層級上。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved